@sasjs/api 0.35.0 → 0.37.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 (46) hide show
  1. package/build/browser.js +616 -64
  2. package/build/cjs/viya/compute.js +280 -0
  3. package/build/cjs/viya/declared.js +38 -0
  4. package/build/cjs/viya/dispatch.js +3 -3
  5. package/build/cjs/viya/files.js +199 -0
  6. package/build/cjs/viya/ids.js +60 -0
  7. package/build/cjs/viya/overlay.js +20 -43
  8. package/build/cjs/viya/ports.js +5 -0
  9. package/build/cjs/viya/seed.js +120 -0
  10. package/build/cjs/viya/service.js +51 -85
  11. package/build/cjs/viya/sessions.js +115 -0
  12. package/build/cjs/viya/unrecorded.js +0 -4
  13. package/build/esm/host/dispatch.d.ts +10 -0
  14. package/build/esm/host/dispatch.d.ts.map +1 -1
  15. package/build/esm/viya/compute.d.ts +39 -0
  16. package/build/esm/viya/compute.d.ts.map +1 -0
  17. package/build/esm/viya/compute.js +276 -0
  18. package/build/esm/viya/declared.d.ts +25 -0
  19. package/build/esm/viya/declared.d.ts.map +1 -0
  20. package/build/esm/viya/declared.js +35 -0
  21. package/build/esm/viya/dispatch.d.ts +1 -1
  22. package/build/esm/viya/dispatch.d.ts.map +1 -1
  23. package/build/esm/viya/dispatch.js +3 -3
  24. package/build/esm/viya/files.d.ts +33 -0
  25. package/build/esm/viya/files.d.ts.map +1 -0
  26. package/build/esm/viya/files.js +196 -0
  27. package/build/esm/viya/ids.d.ts +35 -0
  28. package/build/esm/viya/ids.d.ts.map +1 -0
  29. package/build/esm/viya/ids.js +55 -0
  30. package/build/esm/viya/overlay.d.ts.map +1 -1
  31. package/build/esm/viya/overlay.js +20 -43
  32. package/build/esm/viya/ports.d.ts +12 -0
  33. package/build/esm/viya/ports.d.ts.map +1 -0
  34. package/build/esm/viya/ports.js +1 -0
  35. package/build/esm/viya/seed.d.ts +97 -0
  36. package/build/esm/viya/seed.d.ts.map +1 -0
  37. package/build/esm/viya/seed.js +111 -0
  38. package/build/esm/viya/service.d.ts +0 -16
  39. package/build/esm/viya/service.d.ts.map +1 -1
  40. package/build/esm/viya/service.js +10 -43
  41. package/build/esm/viya/sessions.d.ts +78 -0
  42. package/build/esm/viya/sessions.d.ts.map +1 -0
  43. package/build/esm/viya/sessions.js +109 -0
  44. package/build/esm/viya/unrecorded.d.ts.map +1 -1
  45. package/build/esm/viya/unrecorded.js +0 -4
  46. package/package.json +3 -2
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The compute family: contexts, sessions, jobs and the logs generated for them.
3
+ *
4
+ * These are the operations a `serverType=SASVIYA` application needs before it can
5
+ * do anything: find a context, start a session, submit a program, poll it, read
6
+ * its log. The emulator answers all of them from `EmulatedEstate` - this process -
7
+ * because there is no SAS engine to reach for in a browser and no reason to reach
8
+ * for one here.
9
+ *
10
+ * The context is the one place the emulator answers the question it was asked
11
+ * rather than one it chose: a client names the context it wants by filter and the
12
+ * emulated estate has exactly one, under that name. Its id does not move with the
13
+ * name, so a session can be created for the id the list returned.
14
+ */
15
+ import type { ApiResponse, Services } from '../host/dispatch.js';
16
+ /** The name the emulator answers when a client asks for no particular context. */
17
+ export declare const DEFAULT_CONTEXT_NAME = "Emulated Compute Context";
18
+ /** The one context id this estate mints, whatever name it is asked for. */
19
+ export declare const EMULATED_CONTEXT_ID: string;
20
+ /**
21
+ * The context name a client asked for.
22
+ *
23
+ * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
24
+ * emulated context under the requested name. A second estate is not something an
25
+ * emulator can have, and an empty list would fail a client that has nothing wrong
26
+ * with it.
27
+ */
28
+ export declare const contextNameFrom: (filter: string | undefined) => string;
29
+ export declare const COMPUTE_HANDLERS: Record<string, (context: {
30
+ services: Services;
31
+ request: {
32
+ query?: Record<string, string | undefined>;
33
+ body?: unknown;
34
+ token?: string;
35
+ subject?: unknown;
36
+ };
37
+ params: Record<string, string>;
38
+ }) => Promise<ApiResponse>>;
39
+ //# sourceMappingURL=compute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compute.d.ts","sourceRoot":"","sources":["../../../src/viya/compute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAOhE,kFAAkF;AAClF,eAAO,MAAM,oBAAoB,6BAA6B,CAAA;AAE9D,2EAA2E;AAC3E,eAAO,MAAM,mBAAmB,QAAuC,CAAA;AA+CvE;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,GAAG,SAAS,KAAG,MAM5D,CAAA;AA+GD,eAAO,MAAM,gBAAgB,EAAE,MAAM,CACnC,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CAmM3B,CAAA"}
@@ -0,0 +1,276 @@
1
+ import { ApiError } from '../types.js';
2
+ import { normaliseServerUrl } from './seed.js';
3
+ import { seedOf } from './seed.js';
4
+ import { estateFor } from './sessions.js';
5
+ import { EMULATED_USER, idFor } from './ids.js';
6
+ /** The name the emulator answers when a client asks for no particular context. */
7
+ export const DEFAULT_CONTEXT_NAME = 'Emulated Compute Context';
8
+ /** The one context id this estate mints, whatever name it is asked for. */
9
+ export const EMULATED_CONTEXT_ID = idFor('emulated-context', 'context');
10
+ /**
11
+ * The links a client follows, by rel.
12
+ *
13
+ * The rels are not decoration: the adapter reads `state` to poll a session and a
14
+ * job, `log` to fetch the log, `up` to reach the session from a job. A body that
15
+ * carried only `self` answered 201 and then failed the client, which is how the
16
+ * conformance harness found this.
17
+ */
18
+ const relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: 'GET', type }));
19
+ const linksFor = (uri, type, collection = false, itemType = false) => [
20
+ // the collection link comes first, because that is the order the capture
21
+ // recorded and the item shape assertion walks the first element
22
+ ...(collection
23
+ ? [
24
+ {
25
+ href: `${uri}/members`,
26
+ uri: `${uri}/members`,
27
+ rel: 'members',
28
+ method: 'GET',
29
+ type,
30
+ itemType: type
31
+ }
32
+ ]
33
+ : []),
34
+ {
35
+ href: uri,
36
+ uri,
37
+ rel: 'self',
38
+ method: 'GET',
39
+ type,
40
+ // the log's capture records itemType on its first link, so it is stamped
41
+ // there rather than invented as a members link the estate does not have
42
+ ...(itemType ? { itemType: type } : {})
43
+ }
44
+ ];
45
+ const estateOf = (services) => estateFor(seedOf(services.viya));
46
+ /**
47
+ * The context name a client asked for.
48
+ *
49
+ * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
50
+ * emulated context under the requested name. A second estate is not something an
51
+ * emulator can have, and an empty list would fail a client that has nothing wrong
52
+ * with it.
53
+ */
54
+ export const contextNameFrom = (filter) => {
55
+ if (!filter)
56
+ return DEFAULT_CONTEXT_NAME;
57
+ const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
58
+ return match?.[1] ?? match?.[2] ?? DEFAULT_CONTEXT_NAME;
59
+ };
60
+ const contextBody = (name) => ({
61
+ id: EMULATED_CONTEXT_ID,
62
+ name,
63
+ createdBy: EMULATED_USER.id,
64
+ version: 2,
65
+ links: linksFor(`/compute/contexts/${EMULATED_CONTEXT_ID}`, 'application/vnd.sas.compute.context')
66
+ });
67
+ const sessionBody = (services, session, autoExecLines) => {
68
+ const { id } = session;
69
+ const uri = `/compute/sessions/${id}`;
70
+ return {
71
+ id,
72
+ applicationName: 'emulated',
73
+ owner: EMULATED_USER.id,
74
+ serverId: idFor(normaliseServerUrl(services.viya?.serverUrl) || 'emulated', 'server'),
75
+ state: 'idle',
76
+ attributes: {
77
+ homeDirectory: '/tmp/emulated',
78
+ sessionInactiveTimeout: 3600
79
+ },
80
+ environment: { autoExecLines },
81
+ // the real clock: the adapter computes a session's age from this stamp and
82
+ // expires it against sessionInactiveTimeout
83
+ creationTimeStamp: session.createdAt,
84
+ serviceAPIVersion: 1,
85
+ sessionConditionCode: 0,
86
+ stateElapsedTime: 0,
87
+ version: 2,
88
+ links: relLinks('application/vnd.sas.compute.session', [
89
+ ['self', uri],
90
+ ['state', `${uri}/state`],
91
+ ['log', `${uri}/log`],
92
+ ['jobs', `${uri}/jobs`]
93
+ ])
94
+ };
95
+ };
96
+ const jobBody = (job) => {
97
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}`;
98
+ return {
99
+ id: job.id,
100
+ name: job.name,
101
+ sessionId: job.sessionId,
102
+ state: job.state,
103
+ creationTimeStamp: job.creationTimeStamp,
104
+ ...(job.completedTimeStamp
105
+ ? { completedTimeStamp: job.completedTimeStamp }
106
+ : {}),
107
+ jobConditionCode: 0,
108
+ stateElapsedTime: 1,
109
+ listingStatistics: {
110
+ lineCount: job.log.length,
111
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
112
+ },
113
+ logStatistics: {
114
+ lineCount: job.log.length,
115
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
116
+ },
117
+ statistics: { systemCpuTime: 0.01, userCpuTime: 0.02 },
118
+ version: 2,
119
+ links: relLinks('application/vnd.sas.compute.job', [
120
+ ['self', uri],
121
+ ['state', `${uri}/state`],
122
+ ['log', `${uri}/log`],
123
+ ['up', `/compute/sessions/${job.sessionId}`]
124
+ ])
125
+ };
126
+ };
127
+ /** The session the request names, or the 404 a client that lost it expects. */
128
+ const sessionOf = (services, id) => {
129
+ const session = estateOf(services).session(id);
130
+ if (!session)
131
+ throw new ApiError(404, `Session with ID '${id}' was not found.`);
132
+ return session;
133
+ };
134
+ const jobOf = (services, sessionId, jobId) => {
135
+ const job = sessionOf(services, sessionId).jobs.get(jobId);
136
+ if (!job)
137
+ throw new ApiError(404, `Job with ID '${jobId}' was not found.`);
138
+ return job;
139
+ };
140
+ /**
141
+ * The `{}` values a request carried, in path order.
142
+ *
143
+ * `dispatchViya` sets `segments` on every request it hands a handler, so there is
144
+ * no absent case to answer - a fallback here would be a branch nothing reaches.
145
+ */
146
+ const segmentsOf = (params) => params.segments;
147
+ export const COMPUTE_HANDLERS = {
148
+ 'GET /compute/contexts': async ({ request }) => {
149
+ const limit = Number(request.query?.limit ?? 0) || 0;
150
+ return {
151
+ status: 200,
152
+ body: {
153
+ accept: 'application/json',
154
+ name: 'contexts',
155
+ start: 0,
156
+ limit,
157
+ count: 1,
158
+ version: 2,
159
+ items: [contextBody(contextNameFrom(request.query?.filter))],
160
+ links: linksFor('/compute/contexts', 'application/vnd.sas.compute.context', true)
161
+ }
162
+ };
163
+ },
164
+ 'POST /compute/contexts/{}/sessions': async ({ services, params, request }) => {
165
+ if (params.id !== EMULATED_CONTEXT_ID)
166
+ throw new ApiError(404, `Context with ID '${params.id}' was not found.`);
167
+ const body = (request.body ?? {});
168
+ const session = estateOf(services).create();
169
+ return {
170
+ status: 201,
171
+ body: sessionBody(services, session, body.environment?.autoExecLines ?? [])
172
+ };
173
+ },
174
+ 'GET /compute/sessions/{}/state': async ({ services, params }) => {
175
+ sessionOf(services, params.id);
176
+ // a bare enum, not an object: the adapter calls `.trim()` on the answer, and
177
+ // the capture recorded no shape here because there is no JSON body
178
+ return { status: 200, body: 'idle' };
179
+ },
180
+ 'DELETE /compute/sessions/{}': async ({ services, params }) => {
181
+ sessionOf(services, params.id);
182
+ estateOf(services).remove(params.id);
183
+ return { status: 204, body: undefined };
184
+ },
185
+ 'POST /compute/sessions/{}/jobs': async ({ services, params, request }) => {
186
+ const session = sessionOf(services, params.id);
187
+ const body = (request.body ?? {});
188
+ const job = estateOf(services).submit(session, body);
189
+ const execute = services.viya?.execute;
190
+ // a host with no engine has nothing to run, so the job is finished at once
191
+ if (!execute) {
192
+ job.state = 'completed';
193
+ job.completedTimeStamp = new Date().toISOString();
194
+ return { status: 201, body: jobBody(job) };
195
+ }
196
+ // the 201 is the submission, not the run: the client polls the state link,
197
+ // and `waitForResult: false` is documented to return here and poll later
198
+ job.state = 'running';
199
+ // and there is no log yet: the generated lines are what a host with NO engine
200
+ // answers, including one that says the run completed, so a running job must
201
+ // not advertise them - the run writes the log when it has one
202
+ job.log = [];
203
+ void execute({
204
+ program: body.code ?? '',
205
+ variables: body.variables,
206
+ name: body.name,
207
+ sessionId: session.id
208
+ })
209
+ .then((ran) => {
210
+ job.log = ran.log.split('\n');
211
+ job.state = ran.state ?? 'completed';
212
+ if (ran.webout !== undefined)
213
+ job.webout = ran.webout;
214
+ job.completedTimeStamp = new Date().toISOString();
215
+ })
216
+ .catch((error) => {
217
+ // a run that threw is a failed job with the reason in its log, because a
218
+ // client reads the failure from the state and the log together
219
+ job.state = 'failed';
220
+ job.log = [`ERROR: ${error.message}`];
221
+ job.completedTimeStamp = new Date().toISOString();
222
+ });
223
+ return { status: 201, body: jobBody(job) };
224
+ },
225
+ 'GET /compute/sessions/{}/filerefs/_webout/content': async ({ services, params }) => {
226
+ const session = sessionOf(services, params.id);
227
+ const last = [...session.jobs.values()].pop();
228
+ if (!last)
229
+ throw new ApiError(404, 'This session has no `_webout` yet: nothing has run in it.');
230
+ // the answer belongs to the last job submitted, not to the newest one that
231
+ // happened to produce something: a failed service must not answer with an
232
+ // earlier service's data
233
+ if (last.webout === undefined)
234
+ throw new ApiError(404, last.state === 'running'
235
+ ? `This session has no \`_webout\` yet: job '${last.id}' has not finished.`
236
+ : services.viya?.execute
237
+ ? `This session has no \`_webout\`: job '${last.id}' ran and produced none.`
238
+ : `This session has no \`_webout\`: the host supplied no engine, so no program has run.`);
239
+ return {
240
+ status: 200,
241
+ contents: last.webout,
242
+ headers: { 'content-type': 'text/plain' }
243
+ };
244
+ },
245
+ 'GET /compute/sessions/{}/jobs/{}': async ({ services, params }) => {
246
+ const [sessionId, jobId] = segmentsOf(params);
247
+ return { status: 200, body: jobBody(jobOf(services, sessionId, jobId)) };
248
+ },
249
+ 'GET /compute/sessions/{}/jobs/{}/state': async ({ services, params }) => {
250
+ const [sessionId, jobId] = segmentsOf(params);
251
+ return {
252
+ status: 200,
253
+ body: jobOf(services, sessionId, jobId).state
254
+ };
255
+ },
256
+ 'GET /compute/sessions/{}/jobs/{}/log/content': async ({ services, params, request }) => {
257
+ const [sessionId, jobId] = segmentsOf(params);
258
+ const job = jobOf(services, sessionId, jobId);
259
+ const start = Number(request.query?.start ?? 0) || 0;
260
+ const limit = Number(request.query?.limit ?? 0) || 0;
261
+ const lines = job.log.slice(start, limit ? start + limit : undefined);
262
+ return {
263
+ status: 200,
264
+ body: {
265
+ accept: 'application/json',
266
+ name: 'content',
267
+ start,
268
+ limit: limit || lines.length,
269
+ count: job.log.length,
270
+ version: 2,
271
+ items: lines.map((line) => ({ line, type: 'NOTE', version: 2 })),
272
+ links: linksFor(`/compute/sessions/${job.sessionId}/jobs/${job.id}/log`, 'application/vnd.sas.compute.job.log', false, true)
273
+ }
274
+ };
275
+ }
276
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Operations the emulator must answer that no capture describes.
3
+ *
4
+ * The table is generated from what an estate answered, which is the right rule:
5
+ * a row nobody observed is a claim about a call no client makes. But a client
6
+ * does make some calls that no recording pass reaches, and an emulator that
7
+ * cannot answer them is an emulator an application cannot run on. Those rows are
8
+ * stated here, each with the reason it has no capture, and they pass through the
9
+ * same overlay ratchet as a captured one - so a declared operation still needs a
10
+ * decision about whether this package implements it.
11
+ *
12
+ * They are kept out of `src/viya/table.ts` because that file is generated: a
13
+ * hand-written row in it would be deleted by the next `npm run sync:viya`, and a
14
+ * generator that had to preserve hand edits would stop being a generator.
15
+ */
16
+ import { type ViyaOperation } from './table.js';
17
+ /** A row, and why it is stated rather than recorded. */
18
+ export interface DeclaredOperation extends ViyaOperation {
19
+ /** What no capture could show, and why the client still needs it. */
20
+ declared: string;
21
+ }
22
+ export declare const DECLARED: DeclaredOperation[];
23
+ /** Every operation the emulator answers: what an estate did, plus what it must. */
24
+ export declare const VIYA_OPERATIONS: ViyaOperation[];
25
+ //# sourceMappingURL=declared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"declared.d.ts","sourceRoot":"","sources":["../../../src/viya/declared.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,YAAY,CAAA;AAE3D,wDAAwD;AACxD,MAAM,WAAW,iBAAkB,SAAQ,aAAa;IACtD,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,eAAO,MAAM,QAAQ,EAAE,iBAAiB,EAiBvC,CAAA;AAED,mFAAmF;AACnF,eAAO,MAAM,eAAe,EAAE,aAAa,EAAiC,CAAA"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Operations the emulator must answer that no capture describes.
3
+ *
4
+ * The table is generated from what an estate answered, which is the right rule:
5
+ * a row nobody observed is a claim about a call no client makes. But a client
6
+ * does make some calls that no recording pass reaches, and an emulator that
7
+ * cannot answer them is an emulator an application cannot run on. Those rows are
8
+ * stated here, each with the reason it has no capture, and they pass through the
9
+ * same overlay ratchet as a captured one - so a declared operation still needs a
10
+ * decision about whether this package implements it.
11
+ *
12
+ * They are kept out of `src/viya/table.ts` because that file is generated: a
13
+ * hand-written row in it would be deleted by the next `npm run sync:viya`, and a
14
+ * generator that had to preserve hand edits would stop being a generator.
15
+ */
16
+ import { VIYA_TABLE } from './table.js';
17
+ export const DECLARED = [
18
+ {
19
+ id: 'GET /compute/sessions/{}/filerefs/_webout/content',
20
+ method: 'GET',
21
+ path: '/compute/sessions/{}/filerefs/_webout/content',
22
+ steps: [],
23
+ // what this emulator answers, not what an estate did: 200 with the webout,
24
+ // 404 when no program has run in the session
25
+ statuses: [200, 404],
26
+ queries: [],
27
+ request: { queries: [], body: undefined },
28
+ // the body is the program's `_webout`, which is whatever the program wrote:
29
+ // there is no JSON shape to record
30
+ shape: undefined,
31
+ declared: 'The adapter fetches this only when a run expects a webout (`expectWebout`), and the recording pass submits a `%put` and reads the log instead. Without it an application cannot receive the data its service returns, so the emulator answers it from the job it just ran.'
32
+ }
33
+ ];
34
+ /** Every operation the emulator answers: what an estate did, plus what it must. */
35
+ export const VIYA_OPERATIONS = [...VIYA_TABLE, ...DECLARED];
@@ -12,7 +12,7 @@
12
12
  * evidence about Viya.
13
13
  */
14
14
  import type { ApiRequest, ApiResponse, Services } from '../host/dispatch.js';
15
- import { type ViyaOperation } from './table.js';
15
+ import type { ViyaOperation } from './table.js';
16
16
  /** An answer that states which contract produced it. */
17
17
  export interface ViyaResponse extends ApiResponse {
18
18
  /** Always carries `x-sasjs-emulated`, including on a 404 and a 501. */
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../../src/viya/dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAE5E,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,YAAY,CAAA;AAK3D,wDAAwD;AACxD,MAAM,WAAW,YAAa,SAAQ,WAAW;IAC/C,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,aAAa,CAAA;IACxB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AA4BD,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,MAAM,EACd,MAAM,MAAM,KACX,SAAS,GAAG,SA0Bd,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,QAAQ,MAAM,EACd,MAAM,MAAM,EACZ,UAAS,UAAe,KACvB,OAAO,CAAC,YAAY,CAyFtB,CAAA"}
1
+ {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../../src/viya/dispatch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAE5E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAM/C,wDAAwD;AACxD,MAAM,WAAW,YAAa,SAAQ,WAAW;IAC/C,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAChC;AAED,MAAM,WAAW,SAAS;IACxB,SAAS,EAAE,aAAa,CAAA;IACxB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,EAAE,CAAA;CACnB;AA4BD,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,MAAM,EACd,MAAM,MAAM,KACX,SAAS,GAAG,SA0Bd,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,QAAQ,EAClB,QAAQ,MAAM,EACd,MAAM,MAAM,EACZ,UAAS,UAAe,KACvB,OAAO,CAAC,YAAY,CAyFtB,CAAA"}
@@ -1,10 +1,10 @@
1
1
  import { isApiError } from '../types.js';
2
- import { VIYA_TABLE } from './table.js';
2
+ import { VIYA_OPERATIONS } from './declared.js';
3
3
  import { VIYA_OVERLAY } from './overlay.js';
4
4
  import { VIYA_HANDLERS } from './service.js';
5
5
  import { emulatedHeaders } from './version.js';
6
6
  const escape = (segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
7
- const compiled = VIYA_TABLE.filter((operation) => operation.path.includes('{}')).map((operation) => ({
7
+ const compiled = VIYA_OPERATIONS.filter((operation) => operation.path.includes('{}')).map((operation) => ({
8
8
  operation,
9
9
  pattern: new RegExp('^' +
10
10
  operation.path
@@ -16,7 +16,7 @@ const compiled = VIYA_TABLE.filter((operation) => operation.path.includes('{}'))
16
16
  'i')
17
17
  }));
18
18
  const exact = new Map();
19
- for (const operation of VIYA_TABLE)
19
+ for (const operation of VIYA_OPERATIONS)
20
20
  if (!operation.path.includes('{}'))
21
21
  // keyed in lower case, because the hosts are: express's `case sensitive
22
22
  // routing` is off and the emulated estate has to match what they serve
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The file family: upload, read back, rename, read content, replace content.
3
+ *
4
+ * Five operations, all answered by the drive the package already has, so nothing
5
+ * here stores bytes of its own: an uploaded file is a file in the drive, and
6
+ * reading it back is the drive's read. That is also what makes an upload visible
7
+ * to the folder family - the same estate holds both views.
8
+ *
9
+ * A file id is derived from its path, like a folder id: a client stores the id an
10
+ * upload answered and asks for it later, so the id cannot move between runs.
11
+ */
12
+ import type { ApiResponse, Services } from '../host/dispatch.js';
13
+ /** What an upload answers about itself, whichever operation asked. */
14
+ export interface EmulatedFile {
15
+ name: string;
16
+ path: string;
17
+ size: number;
18
+ }
19
+ export declare const FILE_HANDLERS: Record<string, (context: {
20
+ services: Services;
21
+ request: {
22
+ query?: Record<string, string | undefined>;
23
+ body?: unknown;
24
+ file?: {
25
+ name: string;
26
+ contents: string | Uint8Array;
27
+ };
28
+ token?: string;
29
+ subject?: unknown;
30
+ };
31
+ params: Record<string, string>;
32
+ }) => Promise<ApiResponse>>;
33
+ //# sourceMappingURL=files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../../../src/viya/files.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAOhE,sEAAsE;AACtE,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;CACb;AA4KD,eAAO,MAAM,aAAa,EAAE,MAAM,CAChC,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,IAAI,CAAC,EAAE;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAAA;SAAE,CAAA;QACtD,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CA6E3B,CAAA"}
@@ -0,0 +1,196 @@
1
+ import { ApiError } from '../types.js';
2
+ import { requireDrive } from './ports.js';
3
+ import { EMULATED_NOW, EMULATED_USER, idFor } from './ids.js';
4
+ const contentTypeOf = (name) => {
5
+ if (/\.sas$/i.test(name))
6
+ return 'text/plain';
7
+ if (/\.(json)$/i.test(name))
8
+ return 'application/json';
9
+ if (/\.(csv|txt|log)$/i.test(name))
10
+ return 'text/plain';
11
+ if (/\.(html?)$/i.test(name))
12
+ return 'text/html';
13
+ if (/\.(png)$/i.test(name))
14
+ return 'image/png';
15
+ if (/\.(jpe?g)$/i.test(name))
16
+ return 'image/jpeg';
17
+ return 'application/octet-stream';
18
+ };
19
+ /**
20
+ * What the estate records about a file.
21
+ *
22
+ * `properties` carries the five keys the capture recorded, with the values a
23
+ * client reads rather than placeholders: the three `content.*` flags say what can
24
+ * be done with the file, and `typeRegistrant` says who registered the type.
25
+ */
26
+ const fileBody = (file) => {
27
+ const id = idFor(file.path, 'file');
28
+ const uri = `/files/files/${id}`;
29
+ const contentType = contentTypeOf(file.name);
30
+ return {
31
+ id,
32
+ name: file.name,
33
+ contentType,
34
+ contentDisposition: `attachment; filename="${file.name}"`,
35
+ encoding: 'UTF-8',
36
+ size: file.size,
37
+ fileStatus: 'complete',
38
+ fileVersion: 1,
39
+ version: 2,
40
+ typeDefName: 'file',
41
+ createdBy: EMULATED_USER.id,
42
+ modifiedBy: EMULATED_USER.id,
43
+ creationTimeStamp: EMULATED_NOW,
44
+ modifiedTimeStamp: EMULATED_NOW,
45
+ quarantine: false,
46
+ searchable: true,
47
+ virusDetected: false,
48
+ urlDetected: false,
49
+ properties: {
50
+ 'content.download': 'true',
51
+ 'content.openInBrowser': 'true',
52
+ 'content.preview': 'false',
53
+ sasIconKey: 'file',
54
+ typeRegistrant: EMULATED_USER.id
55
+ },
56
+ links: [
57
+ {
58
+ href: uri,
59
+ uri,
60
+ rel: 'self',
61
+ method: 'GET',
62
+ type: 'application/vnd.sas.file'
63
+ },
64
+ {
65
+ href: `${uri}/content`,
66
+ uri: `${uri}/content`,
67
+ rel: 'content',
68
+ method: 'GET',
69
+ type: 'application/vnd.sas.file.content'
70
+ }
71
+ ]
72
+ };
73
+ };
74
+ /**
75
+ * The bytes in a string, counted rather than measured.
76
+ *
77
+ * `Buffer.byteLength` is not available in the browser build, and the number this
78
+ * returns is the size a client sees, so it has to be right for non-ASCII too.
79
+ */
80
+ const utf8Length = (text) => {
81
+ let bytes = 0;
82
+ for (const character of text) {
83
+ const point = character.codePointAt(0);
84
+ bytes += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;
85
+ }
86
+ return bytes;
87
+ };
88
+ const sizeOf = (contents) => typeof contents === 'string' ? utf8Length(contents) : contents.byteLength;
89
+ /** Every file in the drive, as `path` and name. */
90
+ const filesIn = async (drive) => {
91
+ const walk = (node, found) => {
92
+ if (!node.isFolder)
93
+ found.push({ name: node.name, path: node.relativePath, size: 0 });
94
+ for (const child of node.children)
95
+ walk(child, found);
96
+ return found;
97
+ };
98
+ return walk((await drive.tree('/')).tree, []);
99
+ };
100
+ /**
101
+ * The path a file id names, or the 404 a client with a stale id expects.
102
+ *
103
+ * Resolved against the drive rather than remembered in a map: a rename changes the
104
+ * path and therefore the id, and a map would keep answering for the old one.
105
+ */
106
+ const pathForFileId = async (drive, id) => {
107
+ const file = (await filesIn(drive)).find((candidate) => idFor(candidate.path, 'file') === id);
108
+ if (!file)
109
+ throw new ApiError(404, `File with ID '${id}' was not found.`);
110
+ return file.path;
111
+ };
112
+ const bodyOf = async (drive, path) => {
113
+ const read = await drive.read(path);
114
+ return {
115
+ name: path.split('/').pop(),
116
+ path,
117
+ size: sizeOf(read.contents)
118
+ };
119
+ };
120
+ /** The parent folder a request names, or the root it means by its absence. */
121
+ const parentOf = async (drive, uri) => {
122
+ if (!uri)
123
+ return '/';
124
+ const id = uri.split('/').pop();
125
+ const tree = await drive.tree('/');
126
+ const walk = (node) => {
127
+ if (node.isFolder && idFor(node.relativePath, 'folder') === id)
128
+ return node.relativePath;
129
+ for (const child of node.children) {
130
+ const hit = walk(child);
131
+ if (hit !== undefined)
132
+ return hit;
133
+ }
134
+ return undefined;
135
+ };
136
+ const found = walk(tree.tree);
137
+ if (found === undefined)
138
+ throw new ApiError(404, `Folder with ID '${id}' was not found.`);
139
+ return found;
140
+ };
141
+ export const FILE_HANDLERS = {
142
+ 'POST /files/files': async ({ services, request }) => {
143
+ const drive = requireDrive(services);
144
+ const upload = request.file;
145
+ if (!upload?.name)
146
+ throw new ApiError(400, 'A file named `file` is required.');
147
+ const parent = await parentOf(drive, request.query?.parentFolderUri);
148
+ const path = `${parent}/${upload.name}`.replace(/\/{2,}/g, '/');
149
+ await drive.save(path, upload.contents);
150
+ return { status: 201, body: fileBody(await bodyOf(drive, path)) };
151
+ },
152
+ 'GET /files/files/{}': async ({ services, params }) => {
153
+ const drive = requireDrive(services);
154
+ const path = await pathForFileId(drive, params.id);
155
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
156
+ },
157
+ 'PATCH /files/files/{}': async ({ services, params, request }) => {
158
+ const drive = requireDrive(services);
159
+ const path = await pathForFileId(drive, params.id);
160
+ const body = (request.body ?? {});
161
+ const name = body.name ?? path.split('/').pop();
162
+ const target = `${path.split('/').slice(0, -1).join('/')}/${name}`.replace(/\/{2,}/g, '/');
163
+ if (target !== path)
164
+ await drive.rename(path, target);
165
+ return { status: 200, body: fileBody(await bodyOf(drive, target)) };
166
+ },
167
+ 'GET /files/files/{}/content': async ({ services, params }) => {
168
+ const drive = requireDrive(services);
169
+ const path = await pathForFileId(drive, params.id);
170
+ const read = await drive.read(path);
171
+ // `contents`, not `body`: ApiResponse reserves that field for a raw body,
172
+ // e.g. the driver route that answers with the file itself. A host that maps
173
+ // `body` JSON-encodes the string and declares text/html over a quoted value.
174
+ return {
175
+ status: 200,
176
+ contents: read.contents,
177
+ headers: {
178
+ 'content-type': contentTypeOf(path.split('/').pop())
179
+ }
180
+ };
181
+ },
182
+ 'PUT /files/files/{}/content': async ({ services, params, request }) => {
183
+ const drive = requireDrive(services);
184
+ const path = await pathForFileId(drive, params.id);
185
+ // a host may hand the bytes over as the multipart part or as the body
186
+ const body = request.body;
187
+ const contents = request.file?.contents ??
188
+ (typeof body === 'string'
189
+ ? body
190
+ : body?.contents);
191
+ if (contents === undefined || contents === null)
192
+ throw new ApiError(400, 'File content is required.');
193
+ await drive.update(path, contents);
194
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
195
+ }
196
+ };