@ekanos/sdk 0.18.0 → 0.20.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.
- package/api-report.md +112 -2
- package/dist/components/base-activation-dialog.js +1 -1
- package/dist/components/base-activation-dialog.js.map +1 -1
- package/dist/components/current-return-path.d.ts +16 -1
- package/dist/components/current-return-path.js +18 -1
- package/dist/components/current-return-path.js.map +1 -1
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.js +1 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/oauth-activation-form.js +2 -2
- package/dist/components/oauth-activation-form.js.map +1 -1
- package/dist/components/widgets/ai-prompt-chip.js +1 -1
- package/dist/components/widgets/ai-prompt-chip.js.map +1 -1
- package/dist/components/widgets/widget-ask-bar.js +2 -2
- package/dist/components/widgets/widget-ask-bar.js.map +1 -1
- package/dist/components/widgets/widget-state-components.js +1 -1
- package/dist/components/widgets/widget-state-components.js.map +1 -1
- package/dist/components/widgets/widget.js +19 -4
- package/dist/components/widgets/widget.js.map +1 -1
- package/dist/contract/derive-contract.d.ts +14 -0
- package/dist/contract/derive-contract.js +237 -0
- package/dist/contract/derive-contract.js.map +1 -0
- package/dist/contract/index.d.ts +8 -0
- package/dist/contract/index.js +9 -0
- package/dist/contract/index.js.map +1 -0
- package/dist/contract/synthesize-example.d.ts +6 -0
- package/dist/contract/synthesize-example.js +61 -0
- package/dist/contract/synthesize-example.js.map +1 -0
- package/dist/contract/to-json-schema.d.ts +19 -0
- package/dist/contract/to-json-schema.js +300 -0
- package/dist/contract/to-json-schema.js.map +1 -0
- package/dist/contract/types.d.ts +39 -0
- package/dist/contract/types.js +12 -0
- package/dist/contract/types.js.map +1 -0
- package/dist/experience/client.d.ts +55 -0
- package/dist/experience/client.js +125 -0
- package/dist/experience/client.js.map +1 -0
- package/dist/experience/define-experience.d.ts +172 -0
- package/dist/experience/define-experience.js +147 -0
- package/dist/experience/define-experience.js.map +1 -0
- package/dist/experience/index.d.ts +13 -0
- package/dist/experience/index.js +13 -0
- package/dist/experience/index.js.map +1 -0
- package/dist/experience/runtime.d.ts +54 -0
- package/dist/experience/runtime.js +2 -0
- package/dist/experience/runtime.js.map +1 -0
- package/dist/experience/server.d.ts +11 -0
- package/dist/experience/server.js +47 -0
- package/dist/experience/server.js.map +1 -0
- package/dist/experience/types.d.ts +76 -0
- package/dist/experience/types.js +2 -0
- package/dist/experience/types.js.map +1 -0
- package/dist/experience/workflow-template.d.ts +103 -0
- package/dist/experience/workflow-template.js +132 -0
- package/dist/experience/workflow-template.js.map +1 -0
- package/dist/hooks/use-oauth-connection-status.d.ts +7 -217
- package/dist/hooks/use-oauth-connection-status.js +17 -1
- package/dist/hooks/use-oauth-connection-status.js.map +1 -1
- package/dist/types/integration.d.ts +3 -3
- package/dist/types/integration.js.map +1 -1
- package/eslint.design-preset.mjs +3 -2
- package/eslint.design-rules.mjs +285 -3
- package/eslint.experience-preset.mjs +85 -0
- package/package.json +44 -6
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { UNSUPPORTED_KEYWORDS, findUnsupportedKeywords, } from '@ekanos/integration-schema';
|
|
2
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
3
|
+
import * as z4 from 'zod/v4';
|
|
4
|
+
function isRecord(value) {
|
|
5
|
+
return typeof value === 'object' && value !== null;
|
|
6
|
+
}
|
|
7
|
+
function isZod4(schema) {
|
|
8
|
+
return isRecord(schema) && '_zod' in schema;
|
|
9
|
+
}
|
|
10
|
+
function isZod3(schema) {
|
|
11
|
+
return (isRecord(schema) &&
|
|
12
|
+
!('_zod' in schema) &&
|
|
13
|
+
isRecord(schema._def) &&
|
|
14
|
+
typeof schema._def.typeName === 'string');
|
|
15
|
+
}
|
|
16
|
+
/** Walk a zod graph (either major) and report the first thing JSON Schema cannot hold. */
|
|
17
|
+
function findOpaqueMarker(root) {
|
|
18
|
+
const seen = new Set();
|
|
19
|
+
let found = null;
|
|
20
|
+
const visit = (value, path) => {
|
|
21
|
+
if (found || !isRecord(value) || seen.has(value))
|
|
22
|
+
return;
|
|
23
|
+
seen.add(value);
|
|
24
|
+
if (isZod3(value)) {
|
|
25
|
+
const def = value._def;
|
|
26
|
+
if (def.typeName === 'ZodEffects') {
|
|
27
|
+
const effect = isRecord(def.effect) ? def.effect.type : undefined;
|
|
28
|
+
found = `${effect === 'transform' ? 'transform' : effect === 'preprocess' ? 'preprocess' : 'refinement'} at ${path}`;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (def.typeName === 'ZodLazy') {
|
|
32
|
+
found = `recursive (lazy) schema at ${path}`;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
for (const [key, child] of Object.entries(def)) {
|
|
36
|
+
visit(typeof child === 'function' && key === 'shape'
|
|
37
|
+
? safeCall(child)
|
|
38
|
+
: child, `${path}.${key}`);
|
|
39
|
+
}
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const zod4 = isRecord(value._zod) ? value._zod : null;
|
|
43
|
+
if (zod4) {
|
|
44
|
+
const def = zod4.def;
|
|
45
|
+
if (!def)
|
|
46
|
+
return;
|
|
47
|
+
const type = def.type;
|
|
48
|
+
if (type === 'transform' || type === 'custom') {
|
|
49
|
+
found = `${type === 'transform' ? 'transform' : 'custom check'} at ${path}`;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (type === 'lazy') {
|
|
53
|
+
found = `recursive (lazy) schema at ${path}`;
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (type === 'pipe') {
|
|
57
|
+
const out = isRecord(def.out) && isRecord(def.out._zod)
|
|
58
|
+
? def.out._zod.def
|
|
59
|
+
: null;
|
|
60
|
+
if (isRecord(out) && out.type === 'transform') {
|
|
61
|
+
found = `transform at ${path}`;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (Array.isArray(def.checks)) {
|
|
66
|
+
for (const check of def.checks) {
|
|
67
|
+
const checkDef = isRecord(check) && isRecord(check._zod)
|
|
68
|
+
? check._zod.def
|
|
69
|
+
: null;
|
|
70
|
+
if (checkDef && checkDef.check === 'custom') {
|
|
71
|
+
found = `refinement at ${path}`;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
for (const [key, child] of Object.entries(def)) {
|
|
77
|
+
if (key === 'checks')
|
|
78
|
+
continue;
|
|
79
|
+
visit(child, `${path}.${key}`);
|
|
80
|
+
}
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (Array.isArray(value)) {
|
|
84
|
+
value.forEach((item, index) => visit(item, `${path}[${index}]`));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
// A plain container such as a shape record.
|
|
88
|
+
if (Object.getPrototypeOf(value) === Object.prototype) {
|
|
89
|
+
for (const [key, child] of Object.entries(value)) {
|
|
90
|
+
visit(child, path === '$' ? key : `${path}.${key}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
visit(root, '$');
|
|
95
|
+
return found;
|
|
96
|
+
}
|
|
97
|
+
function safeCall(fn) {
|
|
98
|
+
try {
|
|
99
|
+
return fn();
|
|
100
|
+
}
|
|
101
|
+
catch (_a) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Whether a zod 3 field may be absent from a PARSED value (defaults fill in). */
|
|
106
|
+
function isOutputOptional(field) {
|
|
107
|
+
var _a;
|
|
108
|
+
if (!isRecord(field) || !isRecord(field._def))
|
|
109
|
+
return false;
|
|
110
|
+
const def = field._def;
|
|
111
|
+
switch (def.typeName) {
|
|
112
|
+
case 'ZodOptional':
|
|
113
|
+
return true;
|
|
114
|
+
case 'ZodDefault':
|
|
115
|
+
case 'ZodCatch':
|
|
116
|
+
return false;
|
|
117
|
+
case 'ZodNullable':
|
|
118
|
+
case 'ZodReadonly':
|
|
119
|
+
case 'ZodBranded':
|
|
120
|
+
return isOutputOptional((_a = def.innerType) !== null && _a !== void 0 ? _a : def.type);
|
|
121
|
+
case 'ZodEffects':
|
|
122
|
+
return isOutputOptional(def.schema);
|
|
123
|
+
case 'ZodAny':
|
|
124
|
+
case 'ZodUnknown':
|
|
125
|
+
case 'ZodUndefined':
|
|
126
|
+
case 'ZodVoid':
|
|
127
|
+
return true;
|
|
128
|
+
default:
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Zod 3's emitter escapes characters (`\\:`) that are invalid under the `u`
|
|
134
|
+
* flag the contract validator uses. Drop needless escapes; report a pattern
|
|
135
|
+
* that still does not compile so the half goes opaque.
|
|
136
|
+
*/
|
|
137
|
+
function repairPatterns(node, bad) {
|
|
138
|
+
if (Array.isArray(node)) {
|
|
139
|
+
node.forEach((item) => repairPatterns(item, bad));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (!isRecord(node))
|
|
143
|
+
return;
|
|
144
|
+
if (typeof node.pattern === 'string') {
|
|
145
|
+
const compiles = (pattern) => {
|
|
146
|
+
try {
|
|
147
|
+
new RegExp(pattern, 'u');
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
catch (_a) {
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
if (!compiles(node.pattern)) {
|
|
155
|
+
const unescaped = node.pattern.replace(/\\([^\w\s\\^$.*+?()[\]{}|/-])/g, '$1');
|
|
156
|
+
if (compiles(unescaped))
|
|
157
|
+
node.pattern = unescaped;
|
|
158
|
+
else
|
|
159
|
+
bad.push(node.pattern);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
for (const child of Object.values(node))
|
|
163
|
+
repairPatterns(child, bad);
|
|
164
|
+
}
|
|
165
|
+
function isNeverSchema(node) {
|
|
166
|
+
return (isRecord(node) &&
|
|
167
|
+
Object.keys(node).length === 1 &&
|
|
168
|
+
isRecord(node.not) &&
|
|
169
|
+
Object.keys(node.not).length === 0);
|
|
170
|
+
}
|
|
171
|
+
/** `anyOf` of bare `{type}` alternatives becomes one `type` array, as hand-written JSON Schema has it. */
|
|
172
|
+
function normalize(node) {
|
|
173
|
+
if (!isRecord(node) || Array.isArray(node))
|
|
174
|
+
return node;
|
|
175
|
+
const out = {};
|
|
176
|
+
for (const [key, value] of Object.entries(node)) {
|
|
177
|
+
if (key === '$schema')
|
|
178
|
+
continue;
|
|
179
|
+
if (key === 'properties' && isRecord(value)) {
|
|
180
|
+
out[key] = Object.fromEntries(Object.entries(value).map(([name, child]) => [name, normalize(child)]));
|
|
181
|
+
}
|
|
182
|
+
else if (key === 'items') {
|
|
183
|
+
out[key] = Array.isArray(value) ? value.map(normalize) : normalize(value);
|
|
184
|
+
}
|
|
185
|
+
else if ((key === 'anyOf' || key === 'oneOf') && Array.isArray(value)) {
|
|
186
|
+
// Zod 3 spells an optional member `{ not: {} }` beside the real schema;
|
|
187
|
+
// "may be absent" is the parent's `required`, so the alternative is noise.
|
|
188
|
+
const kept = value.filter((alt) => !isNeverSchema(alt));
|
|
189
|
+
out[key] = kept.map(normalize);
|
|
190
|
+
}
|
|
191
|
+
else if (key === 'additionalProperties') {
|
|
192
|
+
out[key] = normalize(value);
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
out[key] = value;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const only = Array.isArray(out.anyOf) ? out.anyOf : null;
|
|
199
|
+
if (only && only.length === 1 && Object.keys(out).length === 1) {
|
|
200
|
+
return only[0];
|
|
201
|
+
}
|
|
202
|
+
const alternatives = out.anyOf;
|
|
203
|
+
if (Array.isArray(alternatives) &&
|
|
204
|
+
alternatives.length > 1 &&
|
|
205
|
+
Object.keys(out).length === 1 &&
|
|
206
|
+
alternatives.every((alt) => isRecord(alt) &&
|
|
207
|
+
Object.keys(alt).length === 1 &&
|
|
208
|
+
typeof alt.type === 'string')) {
|
|
209
|
+
return { type: alternatives.map((alt) => alt.type) };
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* THE one zod-to-JSON-Schema function (Zod 4 native via `z.toJSONSchema`, Zod 3
|
|
215
|
+
* through `zod-to-json-schema`). Nobody else calls a zod converter.
|
|
216
|
+
*
|
|
217
|
+
* A schema is reported `opaque` when it carries something JSON Schema cannot
|
|
218
|
+
* hold (refinement, transform, recursion), when the conversion throws, when it
|
|
219
|
+
* is not a zod schema, or when the result uses a keyword outside the contract
|
|
220
|
+
* dialect. The schema returned for an opaque half is a best-effort description.
|
|
221
|
+
*/
|
|
222
|
+
export function toJsonSchema(schema, direction = 'output') {
|
|
223
|
+
if (!isZod4(schema) && !isZod3(schema)) {
|
|
224
|
+
return {
|
|
225
|
+
schema: {},
|
|
226
|
+
opaque: true,
|
|
227
|
+
reason: 'the schema is not a zod schema, so it cannot be converted',
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const marker = findOpaqueMarker(schema);
|
|
231
|
+
let raw;
|
|
232
|
+
try {
|
|
233
|
+
if (isZod4(schema)) {
|
|
234
|
+
raw = z4.toJSONSchema(schema, {
|
|
235
|
+
io: direction,
|
|
236
|
+
unrepresentable: 'any',
|
|
237
|
+
reused: 'inline',
|
|
238
|
+
cycles: 'throw',
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
raw = zodToJsonSchema(schema, {
|
|
243
|
+
$refStrategy: 'none',
|
|
244
|
+
target: 'jsonSchema7',
|
|
245
|
+
effectStrategy: 'input',
|
|
246
|
+
postProcess: (json, def) => {
|
|
247
|
+
const typeName = def.typeName;
|
|
248
|
+
if (direction !== 'output' || typeName !== 'ZodObject' || !json)
|
|
249
|
+
return json;
|
|
250
|
+
const shape = def.shape();
|
|
251
|
+
const required = Object.entries(shape)
|
|
252
|
+
.filter(([, field]) => !isOutputOptional(field))
|
|
253
|
+
.map(([key]) => key);
|
|
254
|
+
const next = Object.assign({}, json);
|
|
255
|
+
if (required.length > 0)
|
|
256
|
+
next.required = required;
|
|
257
|
+
else
|
|
258
|
+
delete next.required;
|
|
259
|
+
return next;
|
|
260
|
+
},
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
return {
|
|
266
|
+
schema: {},
|
|
267
|
+
opaque: true,
|
|
268
|
+
reason: `the schema could not be converted: ${error instanceof Error ? error.message : String(error)}`,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
const converted = normalize(raw);
|
|
272
|
+
const badPatterns = [];
|
|
273
|
+
repairPatterns(converted, badPatterns);
|
|
274
|
+
if (badPatterns.length > 0 && !marker) {
|
|
275
|
+
return {
|
|
276
|
+
schema: converted,
|
|
277
|
+
opaque: true,
|
|
278
|
+
reason: `the pattern ${badPatterns[0]} is not a valid regular expression`,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
if (marker) {
|
|
282
|
+
return {
|
|
283
|
+
schema: converted,
|
|
284
|
+
opaque: true,
|
|
285
|
+
reason: `${marker} that the JSON Schema emitter drops`,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
const unsupported = findUnsupportedKeywords(converted);
|
|
289
|
+
if (unsupported.length > 0) {
|
|
290
|
+
return {
|
|
291
|
+
schema: converted,
|
|
292
|
+
opaque: true,
|
|
293
|
+
reason: `uses JSON Schema keywords outside the contract dialect (${unsupported
|
|
294
|
+
.slice(0, 3)
|
|
295
|
+
.join(', ')}; unsupported: ${UNSUPPORTED_KEYWORDS.slice(0, 3).join(', ')}...)`,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
return { schema: converted, opaque: false };
|
|
299
|
+
}
|
|
300
|
+
//# sourceMappingURL=to-json-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"to-json-schema.js","sourceRoot":"","sources":["../../src/contract/to-json-schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL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AM,EAAE,IAAI;YACZ,MAAM,EAAE,GAAG,MAAM,qCAAqC;SACvD,CAAC;IACJ,CAAC;IACD,MAAM,WAAW,GAAG,uBAAuB,CAAC,SAAS,CAAC,CAAC;IACvD,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,OAAO;YACL,MAAM,EAAE,SAAS;YACjB,MAAM,EAAE,IAAI;YACZ,MAAM,EAAE,2DAA2D,WAAW;iBAC3E,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;iBACX,IAAI,CACH,IAAI,CACL,kBAAkB,oBAAoB,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM;SACvE,CAAC;IACJ,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC9C,CAAC","sourcesContent":["import {\n type JsonSchema,\n UNSUPPORTED_KEYWORDS,\n findUnsupportedKeywords,\n} from '@ekanos/integration-schema';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport * as z4 from 'zod/v4';\n\nexport interface ToJsonSchemaResult {\n schema: JsonSchema;\n /** True when the schema could not be represented faithfully. */\n opaque: boolean;\n /** Why, when `opaque`; auto-filled into the contract's `opaqueReason`. */\n reason?: string;\n}\n\nexport type SchemaDirection = 'input' | 'output';\n\ntype Loose = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Loose {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isZod4(schema: unknown): boolean {\n return isRecord(schema) && '_zod' in schema;\n}\n\nfunction isZod3(schema: unknown): boolean {\n return (\n isRecord(schema) &&\n !('_zod' in schema) &&\n isRecord(schema._def) &&\n typeof schema._def.typeName === 'string'\n );\n}\n\n/** Walk a zod graph (either major) and report the first thing JSON Schema cannot hold. */\nfunction findOpaqueMarker(root: unknown): string | null {\n const seen = new Set<unknown>();\n let found: string | null = null;\n\n const visit = (value: unknown, path: string): void => {\n if (found || !isRecord(value) || seen.has(value)) return;\n seen.add(value);\n\n if (isZod3(value)) {\n const def = value._def as Loose;\n if (def.typeName === 'ZodEffects') {\n const effect = isRecord(def.effect) ? def.effect.type : undefined;\n found = `${effect === 'transform' ? 'transform' : effect === 'preprocess' ? 'preprocess' : 'refinement'} at ${path}`;\n return;\n }\n if (def.typeName === 'ZodLazy') {\n found = `recursive (lazy) schema at ${path}`;\n return;\n }\n for (const [key, child] of Object.entries(def)) {\n visit(\n typeof child === 'function' && key === 'shape'\n ? safeCall(child)\n : child,\n `${path}.${key}`,\n );\n }\n return;\n }\n\n const zod4 = isRecord(value._zod) ? (value._zod as Loose) : null;\n if (zod4) {\n const def = zod4.def as Loose | undefined;\n if (!def) return;\n const type = def.type;\n if (type === 'transform' || type === 'custom') {\n found = `${type === 'transform' ? 'transform' : 'custom check'} at ${path}`;\n return;\n }\n if (type === 'lazy') {\n found = `recursive (lazy) schema at ${path}`;\n return;\n }\n if (type === 'pipe') {\n const out =\n isRecord(def.out) && isRecord((def.out as Loose)._zod)\n ? ((def.out as Loose)._zod as Loose).def\n : null;\n if (isRecord(out) && out.type === 'transform') {\n found = `transform at ${path}`;\n return;\n }\n }\n if (Array.isArray(def.checks)) {\n for (const check of def.checks) {\n const checkDef =\n isRecord(check) && isRecord(check._zod)\n ? ((check._zod as Loose).def as Loose)\n : null;\n if (checkDef && checkDef.check === 'custom') {\n found = `refinement at ${path}`;\n return;\n }\n }\n }\n for (const [key, child] of Object.entries(def)) {\n if (key === 'checks') continue;\n visit(child, `${path}.${key}`);\n }\n return;\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, index) => visit(item, `${path}[${index}]`));\n return;\n }\n // A plain container such as a shape record.\n if (Object.getPrototypeOf(value) === Object.prototype) {\n for (const [key, child] of Object.entries(value)) {\n visit(child, path === '$' ? key : `${path}.${key}`);\n }\n }\n };\n\n visit(root, '$');\n return found;\n}\n\nfunction safeCall(fn: unknown): unknown {\n try {\n return (fn as () => unknown)();\n } catch {\n return undefined;\n }\n}\n\n/** Whether a zod 3 field may be absent from a PARSED value (defaults fill in). */\nfunction isOutputOptional(field: unknown): boolean {\n if (!isRecord(field) || !isRecord(field._def)) return false;\n const def = field._def as Loose;\n switch (def.typeName) {\n case 'ZodOptional':\n return true;\n case 'ZodDefault':\n case 'ZodCatch':\n return false;\n case 'ZodNullable':\n case 'ZodReadonly':\n case 'ZodBranded':\n return isOutputOptional(def.innerType ?? def.type);\n case 'ZodEffects':\n return isOutputOptional(def.schema);\n case 'ZodAny':\n case 'ZodUnknown':\n case 'ZodUndefined':\n case 'ZodVoid':\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Zod 3's emitter escapes characters (`\\\\:`) that are invalid under the `u`\n * flag the contract validator uses. Drop needless escapes; report a pattern\n * that still does not compile so the half goes opaque.\n */\nfunction repairPatterns(node: unknown, bad: string[]): void {\n if (Array.isArray(node)) {\n node.forEach((item) => repairPatterns(item, bad));\n return;\n }\n if (!isRecord(node)) return;\n if (typeof node.pattern === 'string') {\n const compiles = (pattern: string) => {\n try {\n new RegExp(pattern, 'u');\n return true;\n } catch {\n return false;\n }\n };\n if (!compiles(node.pattern)) {\n const unescaped = node.pattern.replace(\n /\\\\([^\\w\\s\\\\^$.*+?()[\\]{}|/-])/g,\n '$1',\n );\n if (compiles(unescaped)) node.pattern = unescaped;\n else bad.push(node.pattern);\n }\n }\n for (const child of Object.values(node)) repairPatterns(child, bad);\n}\n\nfunction isNeverSchema(node: unknown): boolean {\n return (\n isRecord(node) &&\n Object.keys(node).length === 1 &&\n isRecord(node.not) &&\n Object.keys(node.not).length === 0\n );\n}\n\n/** `anyOf` of bare `{type}` alternatives becomes one `type` array, as hand-written JSON Schema has it. */\nfunction normalize(node: unknown): unknown {\n if (!isRecord(node) || Array.isArray(node)) return node;\n const out: Loose = {};\n for (const [key, value] of Object.entries(node)) {\n if (key === '$schema') continue;\n if (key === 'properties' && isRecord(value)) {\n out[key] = Object.fromEntries(\n Object.entries(value).map(([name, child]) => [name, normalize(child)]),\n );\n } else if (key === 'items') {\n out[key] = Array.isArray(value) ? value.map(normalize) : normalize(value);\n } else if ((key === 'anyOf' || key === 'oneOf') && Array.isArray(value)) {\n // Zod 3 spells an optional member `{ not: {} }` beside the real schema;\n // \"may be absent\" is the parent's `required`, so the alternative is noise.\n const kept = value.filter((alt) => !isNeverSchema(alt));\n out[key] = kept.map(normalize);\n } else if (key === 'additionalProperties') {\n out[key] = normalize(value);\n } else {\n out[key] = value;\n }\n }\n const only = Array.isArray(out.anyOf) ? out.anyOf : null;\n if (only && only.length === 1 && Object.keys(out).length === 1) {\n return only[0];\n }\n const alternatives = out.anyOf;\n if (\n Array.isArray(alternatives) &&\n alternatives.length > 1 &&\n Object.keys(out).length === 1 &&\n alternatives.every(\n (alt) =>\n isRecord(alt) &&\n Object.keys(alt).length === 1 &&\n typeof alt.type === 'string',\n )\n ) {\n return { type: alternatives.map((alt) => (alt as Loose).type) };\n }\n return out;\n}\n\n/**\n * THE one zod-to-JSON-Schema function (Zod 4 native via `z.toJSONSchema`, Zod 3\n * through `zod-to-json-schema`). Nobody else calls a zod converter.\n *\n * A schema is reported `opaque` when it carries something JSON Schema cannot\n * hold (refinement, transform, recursion), when the conversion throws, when it\n * is not a zod schema, or when the result uses a keyword outside the contract\n * dialect. The schema returned for an opaque half is a best-effort description.\n */\nexport function toJsonSchema(\n schema: unknown,\n direction: SchemaDirection = 'output',\n): ToJsonSchemaResult {\n if (!isZod4(schema) && !isZod3(schema)) {\n return {\n schema: {},\n opaque: true,\n reason: 'the schema is not a zod schema, so it cannot be converted',\n };\n }\n\n const marker = findOpaqueMarker(schema);\n let raw: unknown;\n try {\n if (isZod4(schema)) {\n raw = z4.toJSONSchema(schema as z4.ZodType, {\n io: direction,\n unrepresentable: 'any',\n reused: 'inline',\n cycles: 'throw',\n });\n } else {\n raw = zodToJsonSchema(schema as Parameters<typeof zodToJsonSchema>[0], {\n $refStrategy: 'none',\n target: 'jsonSchema7',\n effectStrategy: 'input',\n postProcess: (json, def) => {\n const typeName = (def as Loose).typeName;\n if (direction !== 'output' || typeName !== 'ZodObject' || !json)\n return json;\n const shape = (\n def as { shape: () => Record<string, unknown> }\n ).shape();\n const required = Object.entries(shape)\n .filter(([, field]) => !isOutputOptional(field))\n .map(([key]) => key);\n const next = { ...(json as Loose) };\n if (required.length > 0) next.required = required;\n else delete next.required;\n return next as typeof json;\n },\n });\n }\n } catch (error) {\n return {\n schema: {},\n opaque: true,\n reason: `the schema could not be converted: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n\n const converted = normalize(raw) as JsonSchema;\n const badPatterns: string[] = [];\n repairPatterns(converted, badPatterns);\n if (badPatterns.length > 0 && !marker) {\n return {\n schema: converted,\n opaque: true,\n reason: `the pattern ${badPatterns[0]} is not a valid regular expression`,\n };\n }\n if (marker) {\n return {\n schema: converted,\n opaque: true,\n reason: `${marker} that the JSON Schema emitter drops`,\n };\n }\n const unsupported = findUnsupportedKeywords(converted);\n if (unsupported.length > 0) {\n return {\n schema: converted,\n opaque: true,\n reason: `uses JSON Schema keywords outside the contract dialect (${unsupported\n .slice(0, 3)\n .join(\n ', ',\n )}; unsupported: ${UNSUPPORTED_KEYWORDS.slice(0, 3).join(', ')}...)`,\n };\n }\n return { schema: converted, opaque: false };\n}\n"]}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Contract } from '@ekanos/integration-schema';
|
|
2
|
+
export type DiagnosticSeverity = 'error' | 'warn' | 'info';
|
|
3
|
+
/** One thing deriveContract noticed. Stable `rule` ids so gates can key on them. */
|
|
4
|
+
export interface ContractDiagnostic {
|
|
5
|
+
rule: 'contract/effect-undeclared' | 'contract/output-schema-missing' | 'contract/output-opaque' | 'contract/input-opaque' | 'contract/example-missing' | 'contract/example-synthesized' | 'contract/example-invalid' | 'contract/event-schema-missing' | 'contract/description-missing' | 'contract/not-sealable';
|
|
6
|
+
severity: DiagnosticSeverity;
|
|
7
|
+
message: string;
|
|
8
|
+
/** `tool/<name>`, `action/<name>` or an event name. */
|
|
9
|
+
operation?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface DeriveContractOptions {
|
|
12
|
+
/** The project's `package.json` version. */
|
|
13
|
+
packageVersion: string;
|
|
14
|
+
/** The authored `ekanos.json` `contract.version`. */
|
|
15
|
+
contractVersion: string;
|
|
16
|
+
/** The committed `contract.json`, to carry `since` forward. */
|
|
17
|
+
previous?: Contract | null;
|
|
18
|
+
/**
|
|
19
|
+
* Recorded output examples keyed `tool/<name>` / `action/<name>`
|
|
20
|
+
* (`contracts/examples/<kind>-<name>.json`). An authored `outputExample`
|
|
21
|
+
* on the definition wins over these.
|
|
22
|
+
*/
|
|
23
|
+
examples?: Readonly<Record<string, unknown>>;
|
|
24
|
+
/**
|
|
25
|
+
* Treat a missing output schema as an error rather than an opaque-output
|
|
26
|
+
* warning. `ekanos contract` sets it for integrations an experience binds.
|
|
27
|
+
*/
|
|
28
|
+
requireOutputSchemas?: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface DeriveContractResult {
|
|
31
|
+
/** Sealed. Present even when `diagnostics` hold errors (the unsealable case aside). */
|
|
32
|
+
contract: Contract;
|
|
33
|
+
diagnostics: ContractDiagnostic[];
|
|
34
|
+
}
|
|
35
|
+
/** Thrown by `deriveContract` when `analyzeContract` reports an error diagnostic. */
|
|
36
|
+
export declare class ContractDerivationError extends Error {
|
|
37
|
+
readonly diagnostics: ContractDiagnostic[];
|
|
38
|
+
constructor(diagnostics: ContractDiagnostic[]);
|
|
39
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Thrown by `deriveContract` when `analyzeContract` reports an error diagnostic. */
|
|
2
|
+
export class ContractDerivationError extends Error {
|
|
3
|
+
constructor(diagnostics) {
|
|
4
|
+
super(diagnostics
|
|
5
|
+
.filter((d) => d.severity === 'error')
|
|
6
|
+
.map((d) => `${d.operation ? `${d.operation}: ` : ''}${d.message}`)
|
|
7
|
+
.join('\n'));
|
|
8
|
+
this.name = 'ContractDerivationError';
|
|
9
|
+
this.diagnostics = diagnostics;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/contract/types.ts"],"names":[],"mappings":"AAiDA,qFAAqF;AACrF,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAEhD,YAAY,WAAiC;QAC3C,KAAK,CACH,WAAW;aACR,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC;aACrC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC;aAClE,IAAI,CAAC,IAAI,CAAC,CACd,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;QACtC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF","sourcesContent":["import type { Contract } from '@ekanos/integration-schema';\n\nexport type DiagnosticSeverity = 'error' | 'warn' | 'info';\n\n/** One thing deriveContract noticed. Stable `rule` ids so gates can key on them. */\nexport interface ContractDiagnostic {\n rule:\n | 'contract/effect-undeclared'\n | 'contract/output-schema-missing'\n | 'contract/output-opaque'\n | 'contract/input-opaque'\n | 'contract/example-missing'\n | 'contract/example-synthesized'\n | 'contract/example-invalid'\n | 'contract/event-schema-missing'\n | 'contract/description-missing'\n | 'contract/not-sealable';\n severity: DiagnosticSeverity;\n message: string;\n /** `tool/<name>`, `action/<name>` or an event name. */\n operation?: string;\n}\n\nexport interface DeriveContractOptions {\n /** The project's `package.json` version. */\n packageVersion: string;\n /** The authored `ekanos.json` `contract.version`. */\n contractVersion: string;\n /** The committed `contract.json`, to carry `since` forward. */\n previous?: Contract | null;\n /**\n * Recorded output examples keyed `tool/<name>` / `action/<name>`\n * (`contracts/examples/<kind>-<name>.json`). An authored `outputExample`\n * on the definition wins over these.\n */\n examples?: Readonly<Record<string, unknown>>;\n /**\n * Treat a missing output schema as an error rather than an opaque-output\n * warning. `ekanos contract` sets it for integrations an experience binds.\n */\n requireOutputSchemas?: boolean;\n}\n\nexport interface DeriveContractResult {\n /** Sealed. Present even when `diagnostics` hold errors (the unsealable case aside). */\n contract: Contract;\n diagnostics: ContractDiagnostic[];\n}\n\n/** Thrown by `deriveContract` when `analyzeContract` reports an error diagnostic. */\nexport class ContractDerivationError extends Error {\n readonly diagnostics: ContractDiagnostic[];\n constructor(diagnostics: ContractDiagnostic[]) {\n super(\n diagnostics\n .filter((d) => d.severity === 'error')\n .map((d) => `${d.operation ? `${d.operation}: ` : ''}${d.message}`)\n .join('\\n'),\n );\n this.name = 'ContractDerivationError';\n this.diagnostics = diagnostics;\n }\n}\n"]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import type { ApprovalToken, ExperienceRuntime, IntegrationInfo } from './runtime.js';
|
|
3
|
+
import type { InputArgs, OperationError, OperationInput, OperationOutput, OperationResult, ReadOperationKey, IntegrationName, WriteOperationKey } from './types.js';
|
|
4
|
+
export declare function ExperienceRuntimeProvider(props: {
|
|
5
|
+
runtime: ExperienceRuntime;
|
|
6
|
+
children?: ReactNode;
|
|
7
|
+
}): import("react").FunctionComponentElement<import("react").ProviderProps<ExperienceRuntime | null>>;
|
|
8
|
+
/** The runtime from the nearest provider; throws a pointed error without one. */
|
|
9
|
+
export declare function useExperienceRuntime(): ExperienceRuntime;
|
|
10
|
+
/** Integration metadata (provenance, run mode) for badges; never for branching logic. */
|
|
11
|
+
export declare function useIntegrationInfo(): IntegrationInfo[];
|
|
12
|
+
export interface UseOperationOptions {
|
|
13
|
+
enabled?: boolean;
|
|
14
|
+
/** Milliseconds a result stays fresh. Default 30s. */
|
|
15
|
+
staleTime?: number;
|
|
16
|
+
refetchInterval?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface UseOperationResult<T> {
|
|
19
|
+
data: T | undefined;
|
|
20
|
+
error: OperationError | undefined;
|
|
21
|
+
isPending: boolean;
|
|
22
|
+
isFetching: boolean;
|
|
23
|
+
refetch: () => Promise<unknown>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Read an operation. Only READ operations type-check here; a write is a
|
|
27
|
+
* compile error (use {@link useOperationMutation}) and, if forced through,
|
|
28
|
+
* a runtime refusal.
|
|
29
|
+
*/
|
|
30
|
+
export declare function useOperation<S extends IntegrationName, K extends ReadOperationKey<S>>(integration: S, op: K, ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]): UseOperationResult<OperationOutput<S, K>>;
|
|
31
|
+
export interface UseOperationMutationOptions {
|
|
32
|
+
/**
|
|
33
|
+
* What a successful write refreshes: this integration's reads (default), every
|
|
34
|
+
* operation query, or nothing.
|
|
35
|
+
*/
|
|
36
|
+
invalidate?: 'integration' | 'all' | false;
|
|
37
|
+
}
|
|
38
|
+
export interface MutateOptions {
|
|
39
|
+
/** A token the runtime minted earlier; normally absent (the runtime asks). */
|
|
40
|
+
approval?: ApprovalToken;
|
|
41
|
+
}
|
|
42
|
+
export interface UseOperationMutationResult<I, O> {
|
|
43
|
+
/** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */
|
|
44
|
+
mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;
|
|
45
|
+
isPending: boolean;
|
|
46
|
+
data: OperationResult<O> | undefined;
|
|
47
|
+
reset: () => void;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Run a WRITE operation. The runtime decides whether a person must approve it
|
|
51
|
+
* (the harness shows its approvals tray; the host runs its approval gate), and
|
|
52
|
+
* the promise resolves once that is settled: `write_not_approved` when it was
|
|
53
|
+
* rejected.
|
|
54
|
+
*/
|
|
55
|
+
export declare function useOperationMutation<S extends IntegrationName, K extends WriteOperationKey<S>>(integration: S, op: K, options?: UseOperationMutationOptions): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>>;
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createContext, createElement, useContext, } from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* `@ekanos/sdk/experience/client` — the hooks an experience widget uses to
|
|
5
|
+
* reach an integration.
|
|
6
|
+
*
|
|
7
|
+
* ```tsx
|
|
8
|
+
* const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });
|
|
9
|
+
* const save = useOperationMutation('news', 'tool/save_idea');
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* Both go through the {@link ExperienceRuntime} the host or the harness
|
|
13
|
+
* supplies via {@link ExperienceRuntimeProvider}. They need a React Query
|
|
14
|
+
* `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.
|
|
15
|
+
*/
|
|
16
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
17
|
+
const RuntimeContext = createContext(null);
|
|
18
|
+
export function ExperienceRuntimeProvider(props) {
|
|
19
|
+
return createElement(RuntimeContext.Provider, { value: props.runtime }, props.children);
|
|
20
|
+
}
|
|
21
|
+
/** The runtime from the nearest provider; throws a pointed error without one. */
|
|
22
|
+
export function useExperienceRuntime() {
|
|
23
|
+
const runtime = useContext(RuntimeContext);
|
|
24
|
+
if (!runtime) {
|
|
25
|
+
throw new Error('useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.');
|
|
26
|
+
}
|
|
27
|
+
return runtime;
|
|
28
|
+
}
|
|
29
|
+
/** Integration metadata (provenance, run mode) for badges; never for branching logic. */
|
|
30
|
+
export function useIntegrationInfo() {
|
|
31
|
+
return useExperienceRuntime().integrations();
|
|
32
|
+
}
|
|
33
|
+
/** A refused call surfaced through React Query: carries the typed refusal. */
|
|
34
|
+
class OperationCallError extends Error {
|
|
35
|
+
constructor(error) {
|
|
36
|
+
super(error.message);
|
|
37
|
+
this.name = 'OperationCallError';
|
|
38
|
+
this.reason = error.reason;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function toOperationError(error) {
|
|
42
|
+
if (error instanceof OperationCallError) {
|
|
43
|
+
return { reason: error.reason, message: error.message };
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
reason: 'execution_failed',
|
|
47
|
+
message: error instanceof Error ? error.message : 'The operation failed.',
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const QUERY_ROOT = 'ekanos-operation';
|
|
51
|
+
/**
|
|
52
|
+
* Read an operation. Only READ operations type-check here; a write is a
|
|
53
|
+
* compile error (use {@link useOperationMutation}) and, if forced through,
|
|
54
|
+
* a runtime refusal.
|
|
55
|
+
*/
|
|
56
|
+
export function useOperation(integration, op, ...args) {
|
|
57
|
+
var _a, _b;
|
|
58
|
+
const runtime = useExperienceRuntime();
|
|
59
|
+
const [input, options] = splitArgs(args);
|
|
60
|
+
const query = useQuery({
|
|
61
|
+
queryKey: [QUERY_ROOT, integration, op, input !== null && input !== void 0 ? input : null],
|
|
62
|
+
enabled: (_a = options === null || options === void 0 ? void 0 : options.enabled) !== null && _a !== void 0 ? _a : true,
|
|
63
|
+
staleTime: (_b = options === null || options === void 0 ? void 0 : options.staleTime) !== null && _b !== void 0 ? _b : 30000,
|
|
64
|
+
refetchInterval: options === null || options === void 0 ? void 0 : options.refetchInterval,
|
|
65
|
+
queryFn: async () => {
|
|
66
|
+
const result = await runtime.call({
|
|
67
|
+
integration,
|
|
68
|
+
op,
|
|
69
|
+
input: input !== null && input !== void 0 ? input : {},
|
|
70
|
+
channel: 'http',
|
|
71
|
+
});
|
|
72
|
+
if (!result.ok)
|
|
73
|
+
throw new OperationCallError(result);
|
|
74
|
+
return result.data;
|
|
75
|
+
},
|
|
76
|
+
retry: false,
|
|
77
|
+
});
|
|
78
|
+
return {
|
|
79
|
+
data: query.data,
|
|
80
|
+
error: query.error ? toOperationError(query.error) : undefined,
|
|
81
|
+
isPending: query.isPending,
|
|
82
|
+
isFetching: query.isFetching,
|
|
83
|
+
refetch: query.refetch,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function splitArgs(args) {
|
|
87
|
+
// `(input?, options?)`: options is recognisable as the trailing object with
|
|
88
|
+
// an option key only when two args are given; one arg is always the input.
|
|
89
|
+
if (args.length >= 2) {
|
|
90
|
+
return [args[0], args[1]];
|
|
91
|
+
}
|
|
92
|
+
return [args[0], undefined];
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Run a WRITE operation. The runtime decides whether a person must approve it
|
|
96
|
+
* (the harness shows its approvals tray; the host runs its approval gate), and
|
|
97
|
+
* the promise resolves once that is settled: `write_not_approved` when it was
|
|
98
|
+
* rejected.
|
|
99
|
+
*/
|
|
100
|
+
export function useOperationMutation(integration, op, options) {
|
|
101
|
+
var _a;
|
|
102
|
+
const runtime = useExperienceRuntime();
|
|
103
|
+
const queryClient = useQueryClient();
|
|
104
|
+
const invalidate = (_a = options === null || options === void 0 ? void 0 : options.invalidate) !== null && _a !== void 0 ? _a : 'integration';
|
|
105
|
+
const mutation = useMutation({
|
|
106
|
+
mutationFn: async (variables) => runtime.call(Object.assign({ integration,
|
|
107
|
+
op, input: variables.input, channel: 'http' }, (variables.approval ? { approval: variables.approval } : {}))),
|
|
108
|
+
onSuccess: async (result) => {
|
|
109
|
+
if (!result.ok || invalidate === false)
|
|
110
|
+
return;
|
|
111
|
+
await queryClient.invalidateQueries({
|
|
112
|
+
queryKey: invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
return {
|
|
117
|
+
mutate: async (input, mutateOptions) => (await mutation.mutateAsync(Object.assign({ input }, ((mutateOptions === null || mutateOptions === void 0 ? void 0 : mutateOptions.approval)
|
|
118
|
+
? { approval: mutateOptions.approval }
|
|
119
|
+
: {})))),
|
|
120
|
+
isPending: mutation.isPending,
|
|
121
|
+
data: mutation.data,
|
|
122
|
+
reset: mutation.reset,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/experience/client.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAEL,aAAa,EACb,aAAa,EACb,UAAU,GACX,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB9E,MAAM,cAAc,GAAG,aAAa,CAA2B,IAAI,CAAC,CAAC;AAErE,MAAM,UAAU,yBAAyB,CAAC,KAGzC;IACC,OAAO,aAAa,CAClB,cAAc,CAAC,QAAQ,EACvB,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,EACxB,KAAK,CAAC,QAAQ,CACf,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,oBAAoB;IAClC,MAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,sJAAsJ,CACvJ,CAAC;IACJ,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,kBAAkB;IAChC,OAAO,oBAAoB,EAAE,CAAC,YAAY,EAAE,CAAC;AAC/C,CAAC;AAED,8EAA8E;AAC9E,MAAM,kBAAmB,SAAQ,KAAK;IAGpC,YAAY,KAAqB;QAC/B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,MAAM,CA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AQ,EAAE,SAAS,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAC/D;QACJ,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YAC1B,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,UAAU,KAAK,KAAK;gBAAE,OAAO;YAC/C,MAAM,WAAW,CAAC,iBAAiB,CAAC;gBAClC,QAAQ,EACN,UAAU,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,EAAE,WAAW,CAAC;aAClE,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;IAEH,OAAO;QACL,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CACrC,CAAC,MAAM,QAAQ,CAAC,WAAW,iBACzB,KAAK,IACF,CAAC,CAAA,aAAa,aAAb,aAAa,uBAAb,aAAa,CAAE,QAAQ;YACzB,CAAC,CAAC,EAAE,QAAQ,EAAE,aAAa,CAAC,QAAQ,EAAE;YACtC,CAAC,CAAC,EAAE,CAAC,EACP,CAA2C;QAC/C,SAAS,EAAE,QAAQ,CAAC,SAAS;QAC7B,IAAI,EAAE,QAAQ,CAAC,IAA0D;QACzE,KAAK,EAAE,QAAQ,CAAC,KAAK;KACtB,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport {\n type ReactNode,\n createContext,\n createElement,\n useContext,\n} from 'react';\n\n/**\n * `@ekanos/sdk/experience/client` — the hooks an experience widget uses to\n * reach an integration.\n *\n * ```tsx\n * const headlines = useOperation('news', 'tool/get_headlines', { limit: 10 });\n * const save = useOperationMutation('news', 'tool/save_idea');\n * ```\n *\n * Both go through the {@link ExperienceRuntime} the host or the harness\n * supplies via {@link ExperienceRuntimeProvider}. They need a React Query\n * `QueryClientProvider` above them, as every `@ekanos/sdk/hooks` hook does.\n */\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport type {\n ApprovalToken,\n ExperienceRuntime,\n IntegrationInfo,\n} from './runtime';\nimport type {\n InputArgs,\n OperationError,\n OperationInput,\n OperationOutput,\n OperationResult,\n ReadOperationKey,\n IntegrationName,\n WriteOperationKey,\n} from './types';\n\nconst RuntimeContext = createContext<ExperienceRuntime | null>(null);\n\nexport function ExperienceRuntimeProvider(props: {\n runtime: ExperienceRuntime;\n children?: ReactNode;\n}) {\n return createElement(\n RuntimeContext.Provider,\n { value: props.runtime },\n props.children,\n );\n}\n\n/** The runtime from the nearest provider; throws a pointed error without one. */\nexport function useExperienceRuntime(): ExperienceRuntime {\n const runtime = useContext(RuntimeContext);\n if (!runtime) {\n throw new Error(\n 'useOperation needs an <ExperienceRuntimeProvider>. Under `ekanos dev` and in the host one is mounted for you; in a unit test wrap the widget in one.',\n );\n }\n\n return runtime;\n}\n\n/** Integration metadata (provenance, run mode) for badges; never for branching logic. */\nexport function useIntegrationInfo(): IntegrationInfo[] {\n return useExperienceRuntime().integrations();\n}\n\n/** A refused call surfaced through React Query: carries the typed refusal. */\nclass OperationCallError extends Error {\n readonly reason: OperationError['reason'];\n\n constructor(error: OperationError) {\n super(error.message);\n this.name = 'OperationCallError';\n this.reason = error.reason;\n }\n}\n\nfunction toOperationError(error: unknown): OperationError {\n if (error instanceof OperationCallError) {\n return { reason: error.reason, message: error.message };\n }\n\n return {\n reason: 'execution_failed',\n message: error instanceof Error ? error.message : 'The operation failed.',\n };\n}\n\nconst QUERY_ROOT = 'ekanos-operation';\n\nexport interface UseOperationOptions {\n enabled?: boolean;\n /** Milliseconds a result stays fresh. Default 30s. */\n staleTime?: number;\n refetchInterval?: number;\n}\n\nexport interface UseOperationResult<T> {\n data: T | undefined;\n error: OperationError | undefined;\n isPending: boolean;\n isFetching: boolean;\n refetch: () => Promise<unknown>;\n}\n\n/**\n * Read an operation. Only READ operations type-check here; a write is a\n * compile error (use {@link useOperationMutation}) and, if forced through,\n * a runtime refusal.\n */\nexport function useOperation<\n S extends IntegrationName,\n K extends ReadOperationKey<S>,\n>(\n integration: S,\n op: K,\n ...args: [...InputArgs<OperationInput<S, K>>, options?: UseOperationOptions]\n): UseOperationResult<OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const [input, options] = splitArgs(args);\n\n const query = useQuery({\n queryKey: [QUERY_ROOT, integration, op, input ?? null],\n enabled: options?.enabled ?? true,\n staleTime: options?.staleTime ?? 30_000,\n refetchInterval: options?.refetchInterval,\n queryFn: async () => {\n const result = await runtime.call({\n integration,\n op,\n input: input ?? {},\n channel: 'http',\n });\n if (!result.ok) throw new OperationCallError(result);\n\n return result.data as OperationOutput<S, K>;\n },\n retry: false,\n });\n\n return {\n data: query.data,\n error: query.error ? toOperationError(query.error) : undefined,\n isPending: query.isPending,\n isFetching: query.isFetching,\n refetch: query.refetch,\n };\n}\n\nfunction splitArgs(\n args: readonly unknown[],\n): [unknown, UseOperationOptions | undefined] {\n // `(input?, options?)`: options is recognisable as the trailing object with\n // an option key only when two args are given; one arg is always the input.\n if (args.length >= 2) {\n return [args[0], args[1] as UseOperationOptions | undefined];\n }\n\n return [args[0], undefined];\n}\n\nexport interface UseOperationMutationOptions {\n /**\n * What a successful write refreshes: this integration's reads (default), every\n * operation query, or nothing.\n */\n invalidate?: 'integration' | 'all' | false;\n}\n\nexport interface MutateOptions {\n /** A token the runtime minted earlier; normally absent (the runtime asks). */\n approval?: ApprovalToken;\n}\n\nexport interface UseOperationMutationResult<I, O> {\n /** Resolves with the typed result; a refusal is `{ ok: false, reason }`, never a throw. */\n mutate: (input: I, options?: MutateOptions) => Promise<OperationResult<O>>;\n isPending: boolean;\n data: OperationResult<O> | undefined;\n reset: () => void;\n}\n\n/**\n * Run a WRITE operation. The runtime decides whether a person must approve it\n * (the harness shows its approvals tray; the host runs its approval gate), and\n * the promise resolves once that is settled: `write_not_approved` when it was\n * rejected.\n */\nexport function useOperationMutation<\n S extends IntegrationName,\n K extends WriteOperationKey<S>,\n>(\n integration: S,\n op: K,\n options?: UseOperationMutationOptions,\n): UseOperationMutationResult<OperationInput<S, K>, OperationOutput<S, K>> {\n const runtime = useExperienceRuntime();\n const queryClient = useQueryClient();\n const invalidate = options?.invalidate ?? 'integration';\n\n const mutation = useMutation({\n mutationFn: async (variables: {\n input: unknown;\n approval?: ApprovalToken;\n }) =>\n runtime.call({\n integration,\n op,\n input: variables.input,\n channel: 'http',\n ...(variables.approval ? { approval: variables.approval } : {}),\n }),\n onSuccess: async (result) => {\n if (!result.ok || invalidate === false) return;\n await queryClient.invalidateQueries({\n queryKey:\n invalidate === 'all' ? [QUERY_ROOT] : [QUERY_ROOT, integration],\n });\n },\n });\n\n return {\n mutate: async (input, mutateOptions) =>\n (await mutation.mutateAsync({\n input,\n ...(mutateOptions?.approval\n ? { approval: mutateOptions.approval }\n : {}),\n })) as OperationResult<OperationOutput<S, K>>,\n isPending: mutation.isPending,\n data: mutation.data as OperationResult<OperationOutput<S, K>> | undefined,\n reset: mutation.reset,\n };\n}\n"]}
|