@mountaya/client 0.0.0-stage → 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.
- package/CHANGELOG.md +104 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +3521 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +1070 -0
- package/dist/admin/index.d.ts +1070 -0
- package/dist/admin/index.js +301 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +8073 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +106 -0
- package/dist/browser.d.ts +106 -0
- package/dist/browser.js +53 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BM526BHG.js +342 -0
- package/dist/chunk-BM526BHG.js.map +1 -0
- package/dist/chunk-D2YEVTG7.js +327 -0
- package/dist/chunk-D2YEVTG7.js.map +1 -0
- package/dist/chunk-OHKVUREN.js +3500 -0
- package/dist/chunk-OHKVUREN.js.map +1 -0
- package/dist/chunk-TDTK2L5H.js +3842 -0
- package/dist/chunk-TDTK2L5H.js.map +1 -0
- package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
- package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
- package/dist/errors-B-GqAtQv.d.cts +75960 -0
- package/dist/errors-B-GqAtQv.d.ts +75960 -0
- package/dist/events/index.cjs +1972 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +781 -0
- package/dist/events/index.d.ts +781 -0
- package/dist/events/index.js +826 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +8072 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
- package/dist/operations.gen-DUD406TV.d.ts +3993 -0
- package/package.json +127 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +232 -0
- package/src/core/engines/sessionToken.ts +870 -0
- package/src/core/rules/auth.ts +1017 -0
- package/src/core/rules/clientHeader.ts +28 -0
- package/src/core/rules/dates.ts +200 -0
- package/src/core/rules/decode.ts +154 -0
- package/src/core/rules/envelope.ts +41 -0
- package/src/core/rules/errors.ts +1486 -0
- package/src/core/rules/graphql.ts +576 -0
- package/src/core/rules/headerValue.ts +42 -0
- package/src/core/rules/idempotencyKey.ts +64 -0
- package/src/core/rules/nullMask.ts +127 -0
- package/src/core/rules/nullMasks.gen.ts +416 -0
- package/src/core/rules/paginate.ts +316 -0
- package/src/core/rules/rateLimit.ts +507 -0
- package/src/core/rules/redaction.ts +219 -0
- package/src/core/rules/resourceRef.ts +110 -0
- package/src/core/rules/responseBody.ts +492 -0
- package/src/core/rules/retry.ts +386 -0
- package/src/core/rules/selection.ts +416 -0
- package/src/core/rules/sessionAnswer.ts +90 -0
- package/src/core/rules/sessionSchedule.ts +131 -0
- package/src/core/rules/sessionWait.ts +112 -0
- package/src/core/rules/transport.ts +2386 -0
- package/src/core/rules/version.gen.ts +16 -0
- package/src/core/rules/webAddress.ts +165 -0
- package/src/core/rules/webAddresses.gen.ts +30 -0
- package/src/data/operations.gen.ts +603 -0
- package/src/data/schema.gen.ts +8078 -0
- package/src/data/selection.gen.ts +472 -0
- package/src/events/index.ts +67 -0
- package/src/events/rules/agent.ts +439 -0
- package/src/events/rules/collab.ts +554 -0
- package/src/events/rules/collabNulls.gen.ts +17 -0
- package/src/events/rules/eventStream.ts +94 -0
- package/src/events/rules/openSseStream.ts +594 -0
- package/src/events/rules/sse.ts +349 -0
- package/src/index.ts +231 -0
- package/src/rest/adminOperations.gen.ts +70 -0
- package/src/rest/adminResources.gen.ts +136 -0
- package/src/rest/coreOperations.gen.ts +74 -0
- package/src/rest/coreResources.gen.ts +244 -0
- package/src/rest/dates.gen.ts +217 -0
- package/src/rest/operations.gen.ts +4341 -0
- package/src/rest/resources.gen.ts +369 -0
- package/src/rest/schema.gen.ts +56840 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8408 -0
- package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
- package/src/webhooks/rules/webhookEvent.ts +38 -0
- package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Field selection for the Data API.
|
|
3
|
+
*
|
|
4
|
+
* Every Data API method sends a generated, depth-bounded full selection by default, which
|
|
5
|
+
* is what makes the first call short. That default is also the whole result: a caller who
|
|
6
|
+
* wanted two fields of a route still receives the 3D geometry, every maneuver, and one
|
|
7
|
+
* elevation float per coordinate. `select` is the way to ask for less, and it is the reason the
|
|
8
|
+
* Data API is GraphQL rather than a REST facade.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* const routes = await mountaya.data.directions(input, {
|
|
12
|
+
* select: { routes: { distance: true, duration: true } },
|
|
13
|
+
* });
|
|
14
|
+
* // ^? { routes: { distance: number; duration: number }[] }
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* The narrowing is real in both directions: the document sent carries only those fields,
|
|
18
|
+
* and the type carries only those fields, so reading `routes[0].geometry` afterwards is a
|
|
19
|
+
* compile error rather than a runtime `undefined`.
|
|
20
|
+
*
|
|
21
|
+
* **The shape a caller may select is derived from the generated tree, not from the result
|
|
22
|
+
* type.** Those look interchangeable and are not: `geometry` is typed as a GeoJSON object,
|
|
23
|
+
* so a `Selection` derived from the result type would happily offer to recurse into
|
|
24
|
+
* `coordinates` and `type`, fields the GraphQL scalar has no sub-selection for and the
|
|
25
|
+
* server would reject. The tree knows what is a leaf; the result type only knows what is
|
|
26
|
+
* an object. Deriving from the tree makes leaf-ness identical at the type level and at
|
|
27
|
+
* runtime, from one source.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { describeType, MountayaError } from "./errors.js";
|
|
31
|
+
import type { RequestOptions } from "./transport.js";
|
|
32
|
+
|
|
33
|
+
/** One level of indentation in a printed document. Matches the generator's. */
|
|
34
|
+
const INDENT = " ";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* FieldTree is a generated selection tree: a leaf is `true`, a composite is a nested
|
|
38
|
+
* tree. Key order is the SDL's field order, and it is load-bearing: see buildDocument.
|
|
39
|
+
*/
|
|
40
|
+
export interface FieldTree {
|
|
41
|
+
readonly [field: string]: true | FieldTree;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Selection is what a caller may pass as `select` for a given operation's tree.
|
|
46
|
+
*
|
|
47
|
+
* Every field is optional; a composite may be `true` to take its whole subtree, or a
|
|
48
|
+
* nested selection to go further. The check is `extends true` rather than
|
|
49
|
+
* `extends FieldTree` so it never depends on a nested `as const` literal being assignable
|
|
50
|
+
* to an index signature.
|
|
51
|
+
*/
|
|
52
|
+
export type Selection<Tree> = {
|
|
53
|
+
readonly [K in keyof Tree]?: Tree[K] extends true ? true : true | Selection<Tree[K]>;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Selected narrows a result type to the fields a selection asked for, unwrapping and
|
|
58
|
+
* re-wrapping arrays and nulls at each level so `{ routes: { distance: true } }` against
|
|
59
|
+
* `{ routes: Route[] }` yields `{ routes: { distance: number }[] }`.
|
|
60
|
+
*
|
|
61
|
+
* The object branch remaps `keyof T` rather than intersecting the two key sets, because a
|
|
62
|
+
* remapped mapping over `keyof T` is homomorphic: it preserves `?` and `readonly` from the
|
|
63
|
+
* result type, which an intersection would silently drop.
|
|
64
|
+
*/
|
|
65
|
+
export type Selected<T, S> = T extends null | undefined
|
|
66
|
+
? T
|
|
67
|
+
: T extends readonly (infer E)[]
|
|
68
|
+
? T extends unknown[]
|
|
69
|
+
? Selected<E, S>[]
|
|
70
|
+
: readonly Selected<E, S>[]
|
|
71
|
+
: {
|
|
72
|
+
[K in keyof T as K extends keyof S ? K : never]: Exclude<
|
|
73
|
+
S[K & keyof S],
|
|
74
|
+
undefined
|
|
75
|
+
> extends true
|
|
76
|
+
? T[K]
|
|
77
|
+
: Selected<T[K], S[K & keyof S]>;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* DataOptions is the second argument of every Data API method.
|
|
82
|
+
*
|
|
83
|
+
* `signal` rides in the bag rather than as a positional parameter, and so does everything
|
|
84
|
+
* after it: a surface that grows a positional argument every time an option arrives is one
|
|
85
|
+
* where the third caller has to remember the order of the first two.
|
|
86
|
+
*
|
|
87
|
+
* It extends the options every REST call takes, so `signal` and the per-call `retry` mean the
|
|
88
|
+
* same thing on all three surfaces, and a knob added there reaches this one too. `select` and
|
|
89
|
+
* the per-call `timeoutMs` are the Data API's own.
|
|
90
|
+
*/
|
|
91
|
+
export interface DataOptions<S> extends RequestOptions {
|
|
92
|
+
/** The fields to return. Omit it to receive the full result. */
|
|
93
|
+
readonly select?: S | undefined;
|
|
94
|
+
/**
|
|
95
|
+
* How long each attempt of this call waits for a response, in whole milliseconds from 1 to
|
|
96
|
+
* 2,147,483,647, in place of the client's `timeoutMs` and of the Data API's own budget: a slow
|
|
97
|
+
* matrix or isochrone call can wait longer, and a search box less, on one client. Refused
|
|
98
|
+
* before the first attempt when outside the range.
|
|
99
|
+
*
|
|
100
|
+
* @default the larger of the client's own `timeoutMs` and the 30 seconds the Data API spends on
|
|
101
|
+
* any operation before it answers a 504 itself, plus five seconds: 35 seconds on a client that
|
|
102
|
+
* keeps its default.
|
|
103
|
+
*/
|
|
104
|
+
readonly timeoutMs?: number | undefined;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* DataResult is a method's return type: the full result when nothing was selected, and
|
|
109
|
+
* the narrowed one when something was. The `[S] extends [undefined]` form is deliberate:
|
|
110
|
+
* a naked check would distribute over a union and answer for each member separately.
|
|
111
|
+
*/
|
|
112
|
+
export type DataResult<T, S> = [S] extends [undefined] ? T : Selected<T, S>;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* SelectionValue is the runtime shape of a selection, once the types are erased.
|
|
116
|
+
*
|
|
117
|
+
* Exported for the caller that builds a selection dynamically (from a config file, a
|
|
118
|
+
* query string, or a model's answer), where the per-operation `Selection` type has nothing
|
|
119
|
+
* to check against. Such a selection is validated when the document is printed rather than
|
|
120
|
+
* by the compiler, which is why the errors name the valid fields.
|
|
121
|
+
*/
|
|
122
|
+
export type SelectionValue = { readonly [field: string]: true | SelectionValue | undefined };
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* MountayaSelectionError is a selection that names something the schema does not have.
|
|
126
|
+
*
|
|
127
|
+
* It is thrown before the request leaves, not after the server refuses, so the message can
|
|
128
|
+
* name the fields that do exist at that level, which is what turns a typo into a fix
|
|
129
|
+
* rather than a round trip and a GraphQL validation error.
|
|
130
|
+
*/
|
|
131
|
+
export class MountayaSelectionError extends MountayaError {
|
|
132
|
+
override readonly name = "MountayaSelectionError";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The most distinct selections whose documents are kept for one tree.
|
|
137
|
+
*
|
|
138
|
+
* A generated tree answers a closed set of selections in any real application, and would need
|
|
139
|
+
* no bound. A selection built at runtime (from a config file, a query string, a model's answer)
|
|
140
|
+
* opens it, so the cap turns a map that only grows into a warm cache that occasionally misses.
|
|
141
|
+
*/
|
|
142
|
+
const MAX_MEMOISED_DOCUMENTS = 256;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Printed documents, memoised by the CONTENT of the selection that produced them, per tree.
|
|
146
|
+
*
|
|
147
|
+
* Printing walks the tree and concatenates a string per field, so a narrowed call pays it on
|
|
148
|
+
* every call, and the calls that narrow are the ones made in a loop: a list re-fetching on each
|
|
149
|
+
* keystroke, a map refreshing per camera move, a batch walking a thousand rows. The document
|
|
150
|
+
* those produce is identical every time, because it is a pure function of the operation, the
|
|
151
|
+
* tree and the selection.
|
|
152
|
+
*
|
|
153
|
+
* Keyed by content rather than by the selection object: `readonly` stops a caller writing to a
|
|
154
|
+
* selection it typed, and nothing more, so a selection built from a config object or edited
|
|
155
|
+
* through a mutable reference changes under an identity key and the memo answers with the
|
|
156
|
+
* document printed before the edit. The key is {@link selectionKey}, a walk of the members the
|
|
157
|
+
* selection names, which is far shorter than the print's walk of the tree at every level it
|
|
158
|
+
* selects, and a selection written inline at the call site hits as a hoisted one does.
|
|
159
|
+
*
|
|
160
|
+
* Weak by tree, so a tree built at runtime takes its documents with it, and the tree is part of
|
|
161
|
+
* the key at all because the document depends on it: two trees answering to one operation name
|
|
162
|
+
* must not answer with each other's document. The inner key carries the operation and the input
|
|
163
|
+
* type, which the document spells as well.
|
|
164
|
+
*/
|
|
165
|
+
const documents = new WeakMap<FieldTree, Map<string, string>>();
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* selectionKey spells a selection's content as a string, walking it along `tree` as the printer
|
|
169
|
+
* does, or answers undefined for a selection the memo does not hold.
|
|
170
|
+
*
|
|
171
|
+
* It reads what the printer reads: each own member, `true` or a nested selection, and skips a
|
|
172
|
+
* member that is `undefined`. It descends only where the tree has a composite, so the tree's depth
|
|
173
|
+
* bounds it, as it bounds the printer: a selection that holds itself, or one nested deeper than the
|
|
174
|
+
* tree, ends the walk where the tree ends rather than at the stack's limit. Anything the tree does
|
|
175
|
+
* not answer (a member it lacks, a nested selection on a leaf, a value other than `true` or an
|
|
176
|
+
* object, a prototype other than a plain object's) is not held, so a selection the printer may read
|
|
177
|
+
* differently from this walk is printed every time rather than answered from a key that does not
|
|
178
|
+
* describe it. The printer then refuses what it cannot print, as it would have anyway.
|
|
179
|
+
*/
|
|
180
|
+
const selectionKey = (selection: object, tree: FieldTree): string | undefined => {
|
|
181
|
+
const prototype: unknown = Object.getPrototypeOf(selection);
|
|
182
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let key = "{";
|
|
187
|
+
for (const [name, picked] of Object.entries(selection)) {
|
|
188
|
+
if (picked === undefined) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const node = Object.hasOwn(tree, name) ? tree[name] : undefined;
|
|
193
|
+
if (node === undefined) {
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (picked === true) {
|
|
198
|
+
key += `${JSON.stringify(name)}:true,`;
|
|
199
|
+
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (node === true || typeof picked !== "object" || picked === null) {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const nested = selectionKey(picked, node);
|
|
208
|
+
if (nested === undefined) {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
key += `${JSON.stringify(name)}:${nested},`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return `${key}}`;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* documentFor picks the document an operation should send.
|
|
220
|
+
*
|
|
221
|
+
* Without a selection it returns the generated full-selection string verbatim rather than
|
|
222
|
+
* reprinting it: that is the path every un-narrowed call takes, and returning the
|
|
223
|
+
* generated bytes means the default cannot drift from what the catalog committed. With one, it
|
|
224
|
+
* prints the narrowed document, or answers it from {@link documents} when the same content was
|
|
225
|
+
* printed for the same tree before.
|
|
226
|
+
*/
|
|
227
|
+
export const documentFor = (
|
|
228
|
+
operation: string,
|
|
229
|
+
inputType: string,
|
|
230
|
+
tree: FieldTree,
|
|
231
|
+
fullDocument: string,
|
|
232
|
+
selection: unknown,
|
|
233
|
+
): string => {
|
|
234
|
+
if (selection === undefined) {
|
|
235
|
+
return fullDocument;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// A selection that is not an object is off-contract and has no content to key on. It goes
|
|
239
|
+
// straight to the printer, which is what names the fields that DO exist at that level: the
|
|
240
|
+
// memo must not turn a diagnosable mistake into a different error.
|
|
241
|
+
if (typeof selection !== "object" || selection === null) {
|
|
242
|
+
return printDocument(operation, inputType, tree, selection);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const content = selectionKey(selection, tree);
|
|
246
|
+
if (content === undefined) {
|
|
247
|
+
return printDocument(operation, inputType, tree, selection);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const key = `${operation}\u0000${inputType}\u0000${content}`;
|
|
251
|
+
const memo = documents.get(tree) ?? new Map<string, string>();
|
|
252
|
+
const memoised = memo.get(key);
|
|
253
|
+
if (memoised !== undefined) {
|
|
254
|
+
return memoised;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Printed before anything is stored, so a selection that names a field the schema does not
|
|
258
|
+
// have throws on every call rather than only the first. A memo that cached the failure
|
|
259
|
+
// would be a memo of nothing; one that cached nothing and reported success once would be
|
|
260
|
+
// worse.
|
|
261
|
+
const document = printDocument(operation, inputType, tree, selection);
|
|
262
|
+
|
|
263
|
+
if (memo.size >= MAX_MEMOISED_DOCUMENTS) {
|
|
264
|
+
// A Map iterates in insertion order, so this is the least recently added entry.
|
|
265
|
+
const oldest = memo.keys().next().value;
|
|
266
|
+
if (oldest !== undefined) {
|
|
267
|
+
memo.delete(oldest);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
memo.set(key, document);
|
|
272
|
+
documents.set(tree, memo);
|
|
273
|
+
|
|
274
|
+
return document;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* buildDocument prints a narrowed document for an operation.
|
|
279
|
+
*
|
|
280
|
+
* Asked for every field, the output is byte-identical to the generated full selection, which
|
|
281
|
+
* `data/selection.test.ts` asserts by rebuilding every full selection and comparing it to the
|
|
282
|
+
* generated string. Both walk the tree, so field order comes from the SDL and never from
|
|
283
|
+
* the order the caller listed its fields: two callers selecting the same fields send the
|
|
284
|
+
* same bytes, and therefore share one automatic-persisted-query entry on the Data API.
|
|
285
|
+
*/
|
|
286
|
+
export const buildDocument = (
|
|
287
|
+
operation: string,
|
|
288
|
+
inputType: string,
|
|
289
|
+
tree: FieldTree,
|
|
290
|
+
selection: SelectionValue,
|
|
291
|
+
): string => printDocument(operation, inputType, tree, selection);
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* printDocument is {@link buildDocument} over a selection as it arrived, which a caller outside the
|
|
295
|
+
* compiler can have built as anything: it is checked level by level as it is printed.
|
|
296
|
+
*/
|
|
297
|
+
const printDocument = (
|
|
298
|
+
operation: string,
|
|
299
|
+
inputType: string,
|
|
300
|
+
tree: FieldTree,
|
|
301
|
+
selection: unknown,
|
|
302
|
+
): string => {
|
|
303
|
+
const body = printSelection(operation, tree, selection, 1);
|
|
304
|
+
if (body === "") {
|
|
305
|
+
throw new MountayaSelectionError(`${operation}: a selection must name at least one field`);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
return `query ${exportName(operation)}($input: ${inputType}) {\n${INDENT}${operation}(input: $input) {\n${body}${INDENT}}\n}\n`;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* printSelection renders the body of one selection set. `selection` undefined means take
|
|
313
|
+
* everything below this point, which is both the default document and what `true` on a
|
|
314
|
+
* composite expands to.
|
|
315
|
+
*/
|
|
316
|
+
const printSelection = (at: string, tree: FieldTree, selection: unknown, depth: number): string => {
|
|
317
|
+
if (selection !== undefined) {
|
|
318
|
+
assertSelectable(at, tree, selection);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const indent = INDENT.repeat(depth + 1);
|
|
322
|
+
|
|
323
|
+
let out = "";
|
|
324
|
+
for (const [name, node] of Object.entries(tree)) {
|
|
325
|
+
const picked = selection === undefined ? true : selection[name];
|
|
326
|
+
if (picked === undefined) {
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (node === true) {
|
|
331
|
+
out += `${indent}${name}\n`;
|
|
332
|
+
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const sub = printSelection(
|
|
337
|
+
`${at}.${name}`,
|
|
338
|
+
node,
|
|
339
|
+
picked === true ? undefined : picked,
|
|
340
|
+
depth + 1,
|
|
341
|
+
);
|
|
342
|
+
if (sub === "") {
|
|
343
|
+
throw new MountayaSelectionError(`${at}.${name}: a selection must name at least one field`);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
out += `${indent}${name} {\n${sub}${indent}}\n`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return out;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
/** isSelectionValue reports whether a value is a selection: an object that is not an array. */
|
|
353
|
+
const isSelectionValue = (value: unknown): value is SelectionValue =>
|
|
354
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
355
|
+
|
|
356
|
+
/** spell names a refused selection member: a primitive by its value, an object by its type. */
|
|
357
|
+
const spell = (value: unknown): string => {
|
|
358
|
+
if (typeof value === "string") {
|
|
359
|
+
return JSON.stringify(value);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
return typeof value === "object" || typeof value === "function"
|
|
363
|
+
? describeType(value)
|
|
364
|
+
: String(value);
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* assertSelectable refuses what a selection level cannot print: a selection that is no object, a
|
|
369
|
+
* key the tree does not have as its own (a name every object inherits included), a member that
|
|
370
|
+
* is neither `true` nor a selection (`false`, `null`, a number), and a sub-selection on a leaf.
|
|
371
|
+
* TypeScript already rejects each for a caller who passes a literal, but `select` can arrive from
|
|
372
|
+
* a config file or an agent, where the types were never checked.
|
|
373
|
+
*/
|
|
374
|
+
function assertSelectable(
|
|
375
|
+
at: string,
|
|
376
|
+
tree: FieldTree,
|
|
377
|
+
selection: unknown,
|
|
378
|
+
): asserts selection is SelectionValue {
|
|
379
|
+
if (!isSelectionValue(selection)) {
|
|
380
|
+
throw new MountayaSelectionError(
|
|
381
|
+
`${at}: a selection is an object naming fields, and this one is ${spell(selection)}; valid fields are: ${Object.keys(tree).join(", ")}`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
for (const [name, picked] of Object.entries(selection)) {
|
|
386
|
+
if (picked === undefined) {
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const node = Object.hasOwn(tree, name) ? tree[name] : undefined;
|
|
391
|
+
if (node === undefined) {
|
|
392
|
+
throw new MountayaSelectionError(
|
|
393
|
+
`${at}: unknown field "${name}"; valid fields are: ${Object.keys(tree).join(", ")}`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (picked !== true && !isSelectionValue(picked)) {
|
|
398
|
+
throw new MountayaSelectionError(
|
|
399
|
+
`${at}.${name} is ${spell(picked)}; select a field with true, or leave it out.`,
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
if (node === true && picked !== true) {
|
|
404
|
+
throw new MountayaSelectionError(
|
|
405
|
+
`${at}: field "${name}" is a leaf and takes no sub-selection`,
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* exportName upper-cases an operation name for the document's operation name. Cosmetic,
|
|
413
|
+
* and it matches the generator so the two printers agree byte for byte.
|
|
414
|
+
*/
|
|
415
|
+
const exportName = (name: string): string =>
|
|
416
|
+
name === "" ? name : `${name[0]?.toUpperCase() ?? ""}${name.slice(1)}`;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a mint's answer must hold to be a session: the rule {@link SessionTokenEngine} reads every
|
|
3
|
+
* answer through before it commits one.
|
|
4
|
+
*
|
|
5
|
+
* The mint is the application's own callback over its own endpoint, so its answer is typed as a
|
|
6
|
+
* `Session` and is still whatever that endpoint sent: the JSON body of a 500 read without a look
|
|
7
|
+
* at the status, a proxy's page, `null`. An answer committed unread leaves a surface with no
|
|
8
|
+
* token and no error, waiting on neither.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describeType, MountayaConnectionError } from "./errors.js";
|
|
12
|
+
|
|
13
|
+
/** SessionAnswer is a mint's answer once it is shown to be a session. */
|
|
14
|
+
export interface SessionAnswer {
|
|
15
|
+
/**
|
|
16
|
+
* When the token expires, or undefined where the answer's `expires_at` names no instant: the
|
|
17
|
+
* token is usable and only its lifetime is unknown.
|
|
18
|
+
*/
|
|
19
|
+
readonly expiresAt: Date | undefined;
|
|
20
|
+
/** The session token, a string that is not empty. */
|
|
21
|
+
readonly token: string;
|
|
22
|
+
/**
|
|
23
|
+
* The user the token was minted for: the answer's `user_id`, `null` where the token is minted
|
|
24
|
+
* without `user_id`, and undefined where the answer does not say, which an endpoint that forwards
|
|
25
|
+
* only `{ token, expires_at }` does.
|
|
26
|
+
*/
|
|
27
|
+
readonly userId: string | null | undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What every refusal ends with: the shape to answer, and how an endpoint's failure is told. */
|
|
31
|
+
const REMEDY =
|
|
32
|
+
"Answer the { token, expires_at, user_id } that POST /v1/sessions returns, and reject where your endpoint fails, as a mint that checks the response's status does.";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* isDate tells a `Date` by its tag rather than by its constructor, so one built in another realm
|
|
36
|
+
* (a frame, another context) is read as the instant it is.
|
|
37
|
+
*/
|
|
38
|
+
const isDate = (value: unknown): value is Date =>
|
|
39
|
+
Object.prototype.toString.call(value) === "[object Date]";
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* readSessionAnswer reads a mint's answer as a session, refusing one that holds no token or
|
|
43
|
+
* nothing to read an expiry from.
|
|
44
|
+
*
|
|
45
|
+
* `expires_at` is a `Date` from the REST surface, a string once the application's own endpoint
|
|
46
|
+
* has put it through JSON, and a number where that endpoint writes its instants as milliseconds
|
|
47
|
+
* since the epoch: each is read as `new Date` reads it. One that is present and names no instant
|
|
48
|
+
* keeps its token: the token is usable and only its lifetime is unknown, so the engine re-mints
|
|
49
|
+
* it on the flat margin. One that is absent, or none of the three, is an answer that is no
|
|
50
|
+
* session at all.
|
|
51
|
+
*
|
|
52
|
+
* `user_id` is read as the user the token was minted for: a string names one, `null` names none,
|
|
53
|
+
* and anything else, its absence included, says nothing, so a call that acts as a member is sent
|
|
54
|
+
* for the API to decide rather than refused for a user the answer never stated.
|
|
55
|
+
*
|
|
56
|
+
* The refusal names each member by its type and never by its value, which may be a key.
|
|
57
|
+
*
|
|
58
|
+
* @throws `MountayaConnectionError` for an answer that is not an object, whose `token` is not a
|
|
59
|
+
* string or is empty, or whose `expires_at` is not a string, a number or a `Date`.
|
|
60
|
+
*/
|
|
61
|
+
export const readSessionAnswer = (answer: unknown): SessionAnswer => {
|
|
62
|
+
if (typeof answer !== "object" || answer === null) {
|
|
63
|
+
throw new MountayaConnectionError(
|
|
64
|
+
`mint: the answer is ${describeType(answer)}, so it is no session. ${REMEDY}`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const token: unknown = Reflect.get(answer, "token");
|
|
69
|
+
if (typeof token !== "string" || token === "") {
|
|
70
|
+
throw new MountayaConnectionError(
|
|
71
|
+
`mint: the answer holds no token (token is ${token === "" ? "an empty string" : describeType(token)}), so it is no session. ${REMEDY}`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const expiry: unknown = Reflect.get(answer, "expires_at");
|
|
76
|
+
if (typeof expiry !== "string" && typeof expiry !== "number" && !isDate(expiry)) {
|
|
77
|
+
throw new MountayaConnectionError(
|
|
78
|
+
`mint: the answer holds no expiry to read (expires_at is ${describeType(expiry)}), so it is no session. ${REMEDY}`,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const parsed = new Date(expiry);
|
|
83
|
+
const user: unknown = Reflect.get(answer, "user_id");
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
expiresAt: Number.isNaN(parsed.getTime()) ? undefined : parsed,
|
|
87
|
+
token,
|
|
88
|
+
userId: typeof user === "string" && user !== "" ? user : user === null ? null : undefined,
|
|
89
|
+
};
|
|
90
|
+
};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* When the next mint is due: the arithmetic of the session-token refresh, with no timer in it.
|
|
3
|
+
*
|
|
4
|
+
* {@link SessionTokenEngine} is a machine: it holds a timer, a generation counter and a run of
|
|
5
|
+
* consecutive bad tokens, and none of that is reproducible from a golden file. What IS
|
|
6
|
+
* reproducible is the decision the machine makes at each step: given a token's remaining life,
|
|
7
|
+
* how long until the next mint, and is a timer armed at all. A second language reimplements THAT
|
|
8
|
+
* and drives it with whatever its platform calls a timer.
|
|
9
|
+
*
|
|
10
|
+
* So the decision is a rule and the machine is an engine, which is the split the whole tree is
|
|
11
|
+
* laid out along. The engine imports this and owns the `setTimeout`; `transport.session.refresh`
|
|
12
|
+
* calls this directly with the contract's own inputs. A conformance runner that restated the
|
|
13
|
+
* arithmetic inline and string-matched the constants out of the engine's source would test how
|
|
14
|
+
* a number is spelled rather than what it decides, and would stay green with the engine's
|
|
15
|
+
* scheduling deleted.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** How long before expiry to refresh. A minute absorbs clock skew and a slow mint. */
|
|
19
|
+
export const REFRESH_MARGIN_MS = 60_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Never ask setTimeout for a single wait longer than this.
|
|
23
|
+
*
|
|
24
|
+
* A day-long token would otherwise arm a day-long timer, and a backgrounded or suspended tab
|
|
25
|
+
* throttles or drops one: it wakes holding a token that lapsed hours ago. Long waits are
|
|
26
|
+
* chained through hops of this length instead, and each hop re-reads the wall clock rather than
|
|
27
|
+
* trusting the timer that woke it, so a laptop resuming from sleep refreshes at the first hop
|
|
28
|
+
* instead of on the schedule it slept through.
|
|
29
|
+
*
|
|
30
|
+
* A hop is not a mint. Re-minting at the cap would cost a long-lived tab a call to the
|
|
31
|
+
* application's own endpoint every ten minutes for a token good for hours.
|
|
32
|
+
*
|
|
33
|
+
* It is a property of the driving, not of the decision, which is why {@link refreshSchedule}
|
|
34
|
+
* never reads it: the delay it reports is the whole wait, and chopping that into hops is the
|
|
35
|
+
* engine's job.
|
|
36
|
+
*/
|
|
37
|
+
export const MAX_TIMER_MS = 10 * 60_000;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Never schedule a timer sooner than this.
|
|
41
|
+
*
|
|
42
|
+
* The margin is proportional, so a short-lived token still gets headroom rather than a zero
|
|
43
|
+
* delay, but a token that arrives already expired, or a clock far enough out of step to look
|
|
44
|
+
* that way, leaves no headroom to be proportional about.
|
|
45
|
+
*
|
|
46
|
+
* A flat floor turns that case into a call to the application's own mint endpoint every five
|
|
47
|
+
* seconds for as long as the skew lasts, which is a slower loop rather than an end to one. So
|
|
48
|
+
* the floor is only the FIRST step: each consecutive mint that fails, or answers a token with
|
|
49
|
+
* no usable lifetime, doubles the wait, up to REFRESH_MARGIN_MS. Failed mints and spent tokens
|
|
50
|
+
* count in one run, since either way the endpoint gave nothing to schedule from. The first
|
|
51
|
+
* healthy token resets it, so the cost of a skew or an outage that clears is one short wait
|
|
52
|
+
* rather than a schedule the caller never climbs back out of.
|
|
53
|
+
*/
|
|
54
|
+
export const MIN_TIMER_MS = 5_000;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What the caller knows when it asks for the next delay.
|
|
58
|
+
*
|
|
59
|
+
* The two fields are alternatives rather than a pair, because they answer different questions: a
|
|
60
|
+
* lifetime asks what the token's own headroom implies, and a spent count asks how long to wait
|
|
61
|
+
* when it implied nothing usable, or when the mint brought no token at all. A caller holding both
|
|
62
|
+
* asks twice, in that order, which is exactly the sequence {@link SessionTokenEngine} runs.
|
|
63
|
+
*/
|
|
64
|
+
interface RefreshScheduleInput {
|
|
65
|
+
/**
|
|
66
|
+
* Milliseconds of life left in the token that just arrived.
|
|
67
|
+
*
|
|
68
|
+
* `undefined` is the token whose `expires_at` did not parse: the token itself is fine and
|
|
69
|
+
* only its lifetime is unknown, so it is re-minted on the flat margin rather than treated as
|
|
70
|
+
* spent. A value at or below zero is NOT that case: it is a token that really did arrive with
|
|
71
|
+
* nothing left, and it falls through to `consecutiveSpent`.
|
|
72
|
+
*/
|
|
73
|
+
readonly lifetimeMs?: number | undefined;
|
|
74
|
+
/**
|
|
75
|
+
* How many mints in the current run failed or answered a token with no usable lifetime,
|
|
76
|
+
* counting from one.
|
|
77
|
+
*
|
|
78
|
+
* Asked after a failed mint, and after a lifetime reported `armed: false`. The run resets on the
|
|
79
|
+
* first healthy token, so the wait describes the CURRENT outage or skew rather than every one
|
|
80
|
+
* the process has seen.
|
|
81
|
+
*/
|
|
82
|
+
readonly consecutiveSpent?: number | undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** When to mint next, and whether a timer is armed for it at all. */
|
|
86
|
+
interface RefreshSchedule {
|
|
87
|
+
/**
|
|
88
|
+
* False where the delay did not clear {@link MIN_TIMER_MS}.
|
|
89
|
+
*
|
|
90
|
+
* The delay is still reported, because it is the proportional margin the token earned and a
|
|
91
|
+
* caller may want to say so; what it must not do is arm a timer on it.
|
|
92
|
+
*/
|
|
93
|
+
readonly armed: boolean;
|
|
94
|
+
/** The whole wait in milliseconds, before the engine chops it into {@link MAX_TIMER_MS} hops. */
|
|
95
|
+
readonly delayMs: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* refreshSchedule answers when the next mint is due.
|
|
100
|
+
*
|
|
101
|
+
* The margin is capped at half the token's life. A flat minute of headroom is right for a token
|
|
102
|
+
* that lives hours and wrong for one that lives thirty seconds: it puts the refresh before the
|
|
103
|
+
* mint that produced it, which schedules at zero and mints again immediately, forever. Half a
|
|
104
|
+
* lifetime keeps the headroom proportional, so a short-lived token refreshes often rather than
|
|
105
|
+
* continuously.
|
|
106
|
+
*/
|
|
107
|
+
export const refreshSchedule = ({
|
|
108
|
+
consecutiveSpent,
|
|
109
|
+
lifetimeMs,
|
|
110
|
+
}: RefreshScheduleInput): RefreshSchedule => {
|
|
111
|
+
// A run of spent tokens is answered before a lifetime is, because the caller that has counted
|
|
112
|
+
// one has already established the lifetime told it nothing.
|
|
113
|
+
if (consecutiveSpent !== undefined) {
|
|
114
|
+
return {
|
|
115
|
+
armed: true,
|
|
116
|
+
delayMs: Math.min(REFRESH_MARGIN_MS, MIN_TIMER_MS * 2 ** (consecutiveSpent - 1)),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// An expiry that did not parse. `getTime()` on an Invalid Date is NaN, NaN survives Math.min
|
|
121
|
+
// unchanged and loses every comparison it is put through, so letting it reach the arithmetic
|
|
122
|
+
// below would read as a token with no lifetime left: one page load, and the caller spends the
|
|
123
|
+
// life of the process re-minting a perfectly good token against its OWN endpoint.
|
|
124
|
+
if (lifetimeMs === undefined) {
|
|
125
|
+
return { armed: true, delayMs: REFRESH_MARGIN_MS };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const delayMs = lifetimeMs - Math.min(REFRESH_MARGIN_MS, lifetimeMs / 2);
|
|
129
|
+
|
|
130
|
+
return { armed: delayMs >= MIN_TIMER_MS, delayMs };
|
|
131
|
+
};
|