@sasjs/api 0.35.0 → 0.36.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.
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COMPUTE_HANDLERS = exports.contextNameFrom = exports.EMULATED_CONTEXT_ID = exports.DEFAULT_CONTEXT_NAME = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const seed_js_1 = require("./seed.js");
6
+ const seed_js_2 = require("./seed.js");
7
+ const sessions_js_1 = require("./sessions.js");
8
+ const ids_js_1 = require("./ids.js");
9
+ /** The name the emulator answers when a client asks for no particular context. */
10
+ exports.DEFAULT_CONTEXT_NAME = 'Emulated Compute Context';
11
+ /** The one context id this estate mints, whatever name it is asked for. */
12
+ exports.EMULATED_CONTEXT_ID = (0, ids_js_1.idFor)('emulated-context', 'context');
13
+ /**
14
+ * The links a client follows, by rel.
15
+ *
16
+ * The rels are not decoration: the adapter reads `state` to poll a session and a
17
+ * job, `log` to fetch the log, `up` to reach the session from a job. A body that
18
+ * carried only `self` answered 201 and then failed the client, which is how the
19
+ * conformance harness found this.
20
+ */
21
+ const relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: 'GET', type }));
22
+ const linksFor = (uri, type, collection = false, itemType = false) => [
23
+ // the collection link comes first, because that is the order the capture
24
+ // recorded and the item shape assertion walks the first element
25
+ ...(collection
26
+ ? [
27
+ {
28
+ href: `${uri}/members`,
29
+ uri: `${uri}/members`,
30
+ rel: 'members',
31
+ method: 'GET',
32
+ type,
33
+ itemType: type
34
+ }
35
+ ]
36
+ : []),
37
+ {
38
+ href: uri,
39
+ uri,
40
+ rel: 'self',
41
+ method: 'GET',
42
+ type,
43
+ // the log's capture records itemType on its first link, so it is stamped
44
+ // there rather than invented as a members link the estate does not have
45
+ ...(itemType ? { itemType: type } : {})
46
+ }
47
+ ];
48
+ const estateOf = (services) => (0, sessions_js_1.estateFor)((0, seed_js_2.seedOf)(services.viya));
49
+ /**
50
+ * The context name a client asked for.
51
+ *
52
+ * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
53
+ * emulated context under the requested name. A second estate is not something an
54
+ * emulator can have, and an empty list would fail a client that has nothing wrong
55
+ * with it.
56
+ */
57
+ const contextNameFrom = (filter) => {
58
+ if (!filter)
59
+ return exports.DEFAULT_CONTEXT_NAME;
60
+ const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
61
+ return match?.[1] ?? match?.[2] ?? exports.DEFAULT_CONTEXT_NAME;
62
+ };
63
+ exports.contextNameFrom = contextNameFrom;
64
+ const contextBody = (name) => ({
65
+ id: exports.EMULATED_CONTEXT_ID,
66
+ name,
67
+ createdBy: ids_js_1.EMULATED_USER.id,
68
+ version: 2,
69
+ links: linksFor(`/compute/contexts/${exports.EMULATED_CONTEXT_ID}`, 'application/vnd.sas.compute.context')
70
+ });
71
+ const sessionBody = (services, session, autoExecLines) => {
72
+ const { id } = session;
73
+ const uri = `/compute/sessions/${id}`;
74
+ return {
75
+ id,
76
+ applicationName: 'emulated',
77
+ owner: ids_js_1.EMULATED_USER.id,
78
+ serverId: (0, ids_js_1.idFor)((0, seed_js_1.normaliseServerUrl)(services.viya?.serverUrl) || 'emulated', 'server'),
79
+ state: 'idle',
80
+ attributes: {
81
+ homeDirectory: '/tmp/emulated',
82
+ sessionInactiveTimeout: 3600
83
+ },
84
+ environment: { autoExecLines },
85
+ // the real clock: the adapter computes a session's age from this stamp and
86
+ // expires it against sessionInactiveTimeout
87
+ creationTimeStamp: session.createdAt,
88
+ serviceAPIVersion: 1,
89
+ sessionConditionCode: 0,
90
+ stateElapsedTime: 0,
91
+ version: 2,
92
+ links: relLinks('application/vnd.sas.compute.session', [
93
+ ['self', uri],
94
+ ['state', `${uri}/state`],
95
+ ['log', `${uri}/log`],
96
+ ['jobs', `${uri}/jobs`]
97
+ ])
98
+ };
99
+ };
100
+ const jobBody = (job) => {
101
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}`;
102
+ return {
103
+ id: job.id,
104
+ name: job.name,
105
+ sessionId: job.sessionId,
106
+ state: job.state,
107
+ creationTimeStamp: job.creationTimeStamp,
108
+ completedTimeStamp: job.completedTimeStamp,
109
+ jobConditionCode: 0,
110
+ stateElapsedTime: 1,
111
+ listingStatistics: {
112
+ lineCount: job.log.length,
113
+ modifiedTimeStamp: job.completedTimeStamp
114
+ },
115
+ logStatistics: {
116
+ lineCount: job.log.length,
117
+ modifiedTimeStamp: job.completedTimeStamp
118
+ },
119
+ statistics: { systemCpuTime: 0.01, userCpuTime: 0.02 },
120
+ version: 2,
121
+ links: relLinks('application/vnd.sas.compute.job', [
122
+ ['self', uri],
123
+ ['state', `${uri}/state`],
124
+ ['log', `${uri}/log`],
125
+ ['up', `/compute/sessions/${job.sessionId}`]
126
+ ])
127
+ };
128
+ };
129
+ /** The session the request names, or the 404 a client that lost it expects. */
130
+ const sessionOf = (services, id) => {
131
+ const session = estateOf(services).session(id);
132
+ if (!session)
133
+ throw new types_js_1.ApiError(404, `Session with ID '${id}' was not found.`);
134
+ return session;
135
+ };
136
+ const jobOf = (services, sessionId, jobId) => {
137
+ const job = sessionOf(services, sessionId).jobs.get(jobId);
138
+ if (!job)
139
+ throw new types_js_1.ApiError(404, `Job with ID '${jobId}' was not found.`);
140
+ return job;
141
+ };
142
+ /**
143
+ * The `{}` values a request carried, in path order.
144
+ *
145
+ * `dispatchViya` sets `segments` on every request it hands a handler, so there is
146
+ * no absent case to answer - a fallback here would be a branch nothing reaches.
147
+ */
148
+ const segmentsOf = (params) => params.segments;
149
+ exports.COMPUTE_HANDLERS = {
150
+ 'GET /compute/contexts': async ({ request }) => {
151
+ const limit = Number(request.query?.limit ?? 0) || 0;
152
+ return {
153
+ status: 200,
154
+ body: {
155
+ accept: 'application/json',
156
+ name: 'contexts',
157
+ start: 0,
158
+ limit,
159
+ count: 1,
160
+ version: 2,
161
+ items: [contextBody((0, exports.contextNameFrom)(request.query?.filter))],
162
+ links: linksFor('/compute/contexts', 'application/vnd.sas.compute.context', true)
163
+ }
164
+ };
165
+ },
166
+ 'POST /compute/contexts/{}/sessions': async ({ services, params, request }) => {
167
+ if (params.id !== exports.EMULATED_CONTEXT_ID)
168
+ throw new types_js_1.ApiError(404, `Context with ID '${params.id}' was not found.`);
169
+ const body = (request.body ?? {});
170
+ const session = estateOf(services).create();
171
+ return {
172
+ status: 201,
173
+ body: sessionBody(services, session, body.environment?.autoExecLines ?? [])
174
+ };
175
+ },
176
+ 'GET /compute/sessions/{}/state': async ({ services, params }) => {
177
+ sessionOf(services, params.id);
178
+ // a bare enum, not an object: the adapter calls `.trim()` on the answer, and
179
+ // the capture recorded no shape here because there is no JSON body
180
+ return { status: 200, body: 'idle' };
181
+ },
182
+ 'DELETE /compute/sessions/{}': async ({ services, params }) => {
183
+ sessionOf(services, params.id);
184
+ estateOf(services).remove(params.id);
185
+ return { status: 204, body: undefined };
186
+ },
187
+ 'POST /compute/sessions/{}/jobs': async ({ services, params, request }) => {
188
+ const session = sessionOf(services, params.id);
189
+ const job = estateOf(services).submit(session, (request.body ?? {}));
190
+ return { status: 201, body: jobBody(job) };
191
+ },
192
+ 'GET /compute/sessions/{}/jobs/{}': async ({ services, params }) => {
193
+ const [sessionId, jobId] = segmentsOf(params);
194
+ return { status: 200, body: jobBody(jobOf(services, sessionId, jobId)) };
195
+ },
196
+ 'GET /compute/sessions/{}/jobs/{}/state': async ({ services, params }) => {
197
+ const [sessionId, jobId] = segmentsOf(params);
198
+ return {
199
+ status: 200,
200
+ body: jobOf(services, sessionId, jobId).state
201
+ };
202
+ },
203
+ 'GET /compute/sessions/{}/jobs/{}/log/content': async ({ services, params, request }) => {
204
+ const [sessionId, jobId] = segmentsOf(params);
205
+ const job = jobOf(services, sessionId, jobId);
206
+ const start = Number(request.query?.start ?? 0) || 0;
207
+ const limit = Number(request.query?.limit ?? 0) || 0;
208
+ const lines = job.log.slice(start, limit ? start + limit : undefined);
209
+ return {
210
+ status: 200,
211
+ body: {
212
+ accept: 'application/json',
213
+ name: 'content',
214
+ start,
215
+ limit: limit || lines.length,
216
+ count: job.log.length,
217
+ version: 2,
218
+ items: lines.map((line) => ({ line, type: 'NOTE', version: 2 })),
219
+ links: linksFor(`/compute/sessions/${job.sessionId}/jobs/${job.id}/log`, 'application/vnd.sas.compute.job.log', false, true)
220
+ }
221
+ };
222
+ }
223
+ };
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FILE_HANDLERS = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const ports_js_1 = require("./ports.js");
6
+ const ids_js_1 = require("./ids.js");
7
+ const contentTypeOf = (name) => {
8
+ if (/\.sas$/i.test(name))
9
+ return 'text/plain';
10
+ if (/\.(json)$/i.test(name))
11
+ return 'application/json';
12
+ if (/\.(csv|txt|log)$/i.test(name))
13
+ return 'text/plain';
14
+ if (/\.(html?)$/i.test(name))
15
+ return 'text/html';
16
+ if (/\.(png)$/i.test(name))
17
+ return 'image/png';
18
+ if (/\.(jpe?g)$/i.test(name))
19
+ return 'image/jpeg';
20
+ return 'application/octet-stream';
21
+ };
22
+ /**
23
+ * What the estate records about a file.
24
+ *
25
+ * `properties` carries the five keys the capture recorded, with the values a
26
+ * client reads rather than placeholders: the three `content.*` flags say what can
27
+ * be done with the file, and `typeRegistrant` says who registered the type.
28
+ */
29
+ const fileBody = (file) => {
30
+ const id = (0, ids_js_1.idFor)(file.path, 'file');
31
+ const uri = `/files/files/${id}`;
32
+ const contentType = contentTypeOf(file.name);
33
+ return {
34
+ id,
35
+ name: file.name,
36
+ contentType,
37
+ contentDisposition: `attachment; filename="${file.name}"`,
38
+ encoding: 'UTF-8',
39
+ size: file.size,
40
+ fileStatus: 'complete',
41
+ fileVersion: 1,
42
+ version: 2,
43
+ typeDefName: 'file',
44
+ createdBy: ids_js_1.EMULATED_USER.id,
45
+ modifiedBy: ids_js_1.EMULATED_USER.id,
46
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
47
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
48
+ quarantine: false,
49
+ searchable: true,
50
+ virusDetected: false,
51
+ urlDetected: false,
52
+ properties: {
53
+ 'content.download': 'true',
54
+ 'content.openInBrowser': 'true',
55
+ 'content.preview': 'false',
56
+ sasIconKey: 'file',
57
+ typeRegistrant: ids_js_1.EMULATED_USER.id
58
+ },
59
+ links: [
60
+ {
61
+ href: uri,
62
+ uri,
63
+ rel: 'self',
64
+ method: 'GET',
65
+ type: 'application/vnd.sas.file'
66
+ },
67
+ {
68
+ href: `${uri}/content`,
69
+ uri: `${uri}/content`,
70
+ rel: 'content',
71
+ method: 'GET',
72
+ type: 'application/vnd.sas.file.content'
73
+ }
74
+ ]
75
+ };
76
+ };
77
+ /**
78
+ * The bytes in a string, counted rather than measured.
79
+ *
80
+ * `Buffer.byteLength` is not available in the browser build, and the number this
81
+ * returns is the size a client sees, so it has to be right for non-ASCII too.
82
+ */
83
+ const utf8Length = (text) => {
84
+ let bytes = 0;
85
+ for (const character of text) {
86
+ const point = character.codePointAt(0);
87
+ bytes += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;
88
+ }
89
+ return bytes;
90
+ };
91
+ const sizeOf = (contents) => typeof contents === 'string' ? utf8Length(contents) : contents.byteLength;
92
+ /** Every file in the drive, as `path` and name. */
93
+ const filesIn = async (drive) => {
94
+ const walk = (node, found) => {
95
+ if (!node.isFolder)
96
+ found.push({ name: node.name, path: node.relativePath, size: 0 });
97
+ for (const child of node.children)
98
+ walk(child, found);
99
+ return found;
100
+ };
101
+ return walk((await drive.tree('/')).tree, []);
102
+ };
103
+ /**
104
+ * The path a file id names, or the 404 a client with a stale id expects.
105
+ *
106
+ * Resolved against the drive rather than remembered in a map: a rename changes the
107
+ * path and therefore the id, and a map would keep answering for the old one.
108
+ */
109
+ const pathForFileId = async (drive, id) => {
110
+ const file = (await filesIn(drive)).find((candidate) => (0, ids_js_1.idFor)(candidate.path, 'file') === id);
111
+ if (!file)
112
+ throw new types_js_1.ApiError(404, `File with ID '${id}' was not found.`);
113
+ return file.path;
114
+ };
115
+ const bodyOf = async (drive, path) => {
116
+ const read = await drive.read(path);
117
+ return {
118
+ name: path.split('/').pop(),
119
+ path,
120
+ size: sizeOf(read.contents)
121
+ };
122
+ };
123
+ /** The parent folder a request names, or the root it means by its absence. */
124
+ const parentOf = async (drive, uri) => {
125
+ if (!uri)
126
+ return '/';
127
+ const id = uri.split('/').pop();
128
+ const tree = await drive.tree('/');
129
+ const walk = (node) => {
130
+ if (node.isFolder && (0, ids_js_1.idFor)(node.relativePath, 'folder') === id)
131
+ return node.relativePath;
132
+ for (const child of node.children) {
133
+ const hit = walk(child);
134
+ if (hit !== undefined)
135
+ return hit;
136
+ }
137
+ return undefined;
138
+ };
139
+ const found = walk(tree.tree);
140
+ if (found === undefined)
141
+ throw new types_js_1.ApiError(404, `Folder with ID '${id}' was not found.`);
142
+ return found;
143
+ };
144
+ exports.FILE_HANDLERS = {
145
+ 'POST /files/files': async ({ services, request }) => {
146
+ const drive = (0, ports_js_1.requireDrive)(services);
147
+ const upload = request.file;
148
+ if (!upload?.name)
149
+ throw new types_js_1.ApiError(400, 'A file named `file` is required.');
150
+ const parent = await parentOf(drive, request.query?.parentFolderUri);
151
+ const path = `${parent}/${upload.name}`.replace(/\/{2,}/g, '/');
152
+ await drive.save(path, upload.contents);
153
+ return { status: 201, body: fileBody(await bodyOf(drive, path)) };
154
+ },
155
+ 'GET /files/files/{}': async ({ services, params }) => {
156
+ const drive = (0, ports_js_1.requireDrive)(services);
157
+ const path = await pathForFileId(drive, params.id);
158
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
159
+ },
160
+ 'PATCH /files/files/{}': async ({ services, params, request }) => {
161
+ const drive = (0, ports_js_1.requireDrive)(services);
162
+ const path = await pathForFileId(drive, params.id);
163
+ const body = (request.body ?? {});
164
+ const name = body.name ?? path.split('/').pop();
165
+ const target = `${path.split('/').slice(0, -1).join('/')}/${name}`.replace(/\/{2,}/g, '/');
166
+ if (target !== path)
167
+ await drive.rename(path, target);
168
+ return { status: 200, body: fileBody(await bodyOf(drive, target)) };
169
+ },
170
+ 'GET /files/files/{}/content': async ({ services, params }) => {
171
+ const drive = (0, ports_js_1.requireDrive)(services);
172
+ const path = await pathForFileId(drive, params.id);
173
+ const read = await drive.read(path);
174
+ // `contents`, not `body`: ApiResponse reserves that field for a raw body,
175
+ // e.g. the driver route that answers with the file itself. A host that maps
176
+ // `body` JSON-encodes the string and declares text/html over a quoted value.
177
+ return {
178
+ status: 200,
179
+ contents: read.contents,
180
+ headers: {
181
+ 'content-type': contentTypeOf(path.split('/').pop())
182
+ }
183
+ };
184
+ },
185
+ 'PUT /files/files/{}/content': async ({ services, params, request }) => {
186
+ const drive = (0, ports_js_1.requireDrive)(services);
187
+ const path = await pathForFileId(drive, params.id);
188
+ // a host may hand the bytes over as the multipart part or as the body
189
+ const body = request.body;
190
+ const contents = request.file?.contents ??
191
+ (typeof body === 'string'
192
+ ? body
193
+ : body?.contents);
194
+ if (contents === undefined || contents === null)
195
+ throw new types_js_1.ApiError(400, 'File content is required.');
196
+ await drive.update(path, contents);
197
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
198
+ }
199
+ };
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ /**
3
+ * The values that identify the emulated estate, in one place.
4
+ *
5
+ * They live apart from the handlers because two handler modules need them: the
6
+ * folder family derives a folder id, the compute family derives a context and a
7
+ * server id, and a module that imports the other's handler map to reach them
8
+ * would be a cycle.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.normalisePath = exports.idFor = exports.EMULATED_USER = exports.EMULATED_NOW = void 0;
12
+ /** The emulated clock: a fixed instant, so a body is reproducible. */
13
+ exports.EMULATED_NOW = '2026-01-01T00:00:00.000Z';
14
+ /** The caller the emulated estate reports when a host does not name one. */
15
+ exports.EMULATED_USER = { id: 'emulated-user', name: 'Emulated User' };
16
+ /**
17
+ * A uuid shape from a string, deterministically.
18
+ *
19
+ * Two 32-bit FNV-1a passes give enough of a hash to fill a uuid's fields, and the
20
+ * version/variant nibbles are set so the result is a well-formed v4-shaped id.
21
+ * Collisions are possible in principle and irrelevant here: the id is a handle
22
+ * the emulator hands back, not a uniqueness guarantee.
23
+ */
24
+ const idFor = (path, kind = 'folder') => {
25
+ const hash = (input, seed) => {
26
+ let value = seed;
27
+ for (let index = 0; index < input.length; index++) {
28
+ value ^= input.charCodeAt(index);
29
+ value = Math.imul(value, 16777619) >>> 0;
30
+ }
31
+ return value.toString(16).padStart(8, '0');
32
+ };
33
+ const raw = hash(`${kind}:${path}`, 2166136261) +
34
+ hash(`${kind}:${path}`, 2246822519) +
35
+ hash(`${kind}:${path}`, 3266489917) +
36
+ hash(`${kind}:${path}`, 668265263);
37
+ const hex = raw.slice(0, 32);
38
+ return [
39
+ hex.slice(0, 8),
40
+ hex.slice(8, 12),
41
+ `4${hex.slice(13, 16)}`,
42
+ `a${hex.slice(17, 20)}`,
43
+ hex.slice(20, 32)
44
+ ].join('-');
45
+ };
46
+ exports.idFor = idFor;
47
+ /**
48
+ * One folder path, however it was spelled.
49
+ *
50
+ * The adapter joins a root of '/' to a path of '/app' and sends '//app', which is
51
+ * a different string and - because an id is derived from the path - a different
52
+ * id. A client that then asks for that id is asking about a folder the drive does
53
+ * not have, so every path is collapsed to one spelling before anything derives
54
+ * from it.
55
+ */
56
+ const normalisePath = (path) => {
57
+ const collapsed = `/${path}`.replace(/\/{2,}/g, '/');
58
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, '') : collapsed;
59
+ };
60
+ exports.normalisePath = normalisePath;
@@ -15,14 +15,6 @@ exports.assertOverlayEntries = exports.VIYA_OVERLAY = void 0;
15
15
  * that reaches it learns why rather than that something is unimplemented.
16
16
  */
17
17
  const table_js_1 = require("./table.js");
18
- /**
19
- * The reason the session and file families carry.
20
- *
21
- * They need the session port and the file content routes, which this slice does
22
- * not mount. Saying it once is better than saying it thirteen times in slightly
23
- * different words.
24
- */
25
- const NEEDS_RUNTIME = 'The emulated estate answers folders, identities and types today. This operation needs the session or file port, which the host mounting the emulator has not supplied.';
26
18
  /**
27
19
  * The token endpoint is the host's.
28
20
  *
@@ -41,38 +33,21 @@ exports.VIYA_OVERLAY = {
41
33
  'GET /folders/folders/@myRecycleBin': { implemented: true },
42
34
  'GET /identities/users/@currentUser': { implemented: true },
43
35
  'GET /types/types': { implemented: true },
44
- // declined: the session and file ports
45
- 'GET /compute/contexts': { implemented: false, reason: NEEDS_RUNTIME },
46
- 'POST /compute/contexts/{}/sessions': {
47
- implemented: false,
48
- reason: NEEDS_RUNTIME
49
- },
50
- 'DELETE /compute/sessions/{}': { implemented: false, reason: NEEDS_RUNTIME },
51
- 'POST /compute/sessions/{}/jobs': {
52
- implemented: false,
53
- reason: NEEDS_RUNTIME
54
- },
55
- 'GET /compute/sessions/{}/jobs/{}': {
56
- implemented: false,
57
- reason: NEEDS_RUNTIME
58
- },
59
- 'GET /compute/sessions/{}/jobs/{}/log/content': {
60
- implemented: false,
61
- reason: NEEDS_RUNTIME
62
- },
63
- 'GET /compute/sessions/{}/jobs/{}/state': {
64
- implemented: false,
65
- reason: NEEDS_RUNTIME
66
- },
67
- 'GET /compute/sessions/{}/state': {
68
- implemented: false,
69
- reason: NEEDS_RUNTIME
70
- },
71
- 'POST /files/files': { implemented: false, reason: NEEDS_RUNTIME },
72
- 'GET /files/files/{}': { implemented: false, reason: NEEDS_RUNTIME },
73
- 'PATCH /files/files/{}': { implemented: false, reason: NEEDS_RUNTIME },
74
- 'GET /files/files/{}/content': { implemented: false, reason: NEEDS_RUNTIME },
75
- 'PUT /files/files/{}/content': { implemented: false, reason: NEEDS_RUNTIME },
36
+ // answered here: compute
37
+ 'GET /compute/contexts': { implemented: true },
38
+ 'POST /compute/contexts/{}/sessions': { implemented: true },
39
+ 'DELETE /compute/sessions/{}': { implemented: true },
40
+ 'POST /compute/sessions/{}/jobs': { implemented: true },
41
+ 'GET /compute/sessions/{}/jobs/{}': { implemented: true },
42
+ 'GET /compute/sessions/{}/jobs/{}/log/content': { implemented: true },
43
+ 'GET /compute/sessions/{}/jobs/{}/state': { implemented: true },
44
+ 'GET /compute/sessions/{}/state': { implemented: true },
45
+ // answered here: files
46
+ 'POST /files/files': { implemented: true },
47
+ 'GET /files/files/{}': { implemented: true },
48
+ 'PATCH /files/files/{}': { implemented: true },
49
+ 'GET /files/files/{}/content': { implemented: true },
50
+ 'PUT /files/files/{}/content': { implemented: true },
76
51
  // declined: the host owns the token port
77
52
  'POST /SASLogon/oauth/token': { implemented: false, reason: NEEDS_AUTH }
78
53
  };
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireDrive = void 0;
4
+ const requireDrive = (services) => services.drive;
5
+ exports.requireDrive = requireDrive;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * What the emulated estate derives its generated data from.
4
+ *
5
+ * The emulator cannot execute SAS, so any answer that a real engine would produce
6
+ * - a job log, a listing, a webout - is generated. Generated data is only useful
7
+ * if it is the same data twice: a screenshot taken after a build must still be
8
+ * true after the next one, and a fixture committed today must match the answer
9
+ * tomorrow.
10
+ *
11
+ * The seed is therefore the identity of the estate, and the identity of an estate
12
+ * is the address clients already use to reach it. A target that points at
13
+ * `http://localhost:5000` and a target that points at `http://127.0.0.1:5000` are
14
+ * the same estate spelled two ways, so the address is normalised before it is
15
+ * hashed - and `seed` exists for the two cases where the address is the wrong
16
+ * identity: the estate reached by a different hostname (a container name, a LAN
17
+ * address), and the port that moves between runs (CI picks an ephemeral one).
18
+ *
19
+ * Absent both, every emulated estate shares one seed. That is the only honest
20
+ * default: an emulator with no address has not told us which estate it is.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.drawFrom = exports.drawInt = exports.generator = exports.seedOf = exports.hash = exports.normaliseServerUrl = exports.DEFAULT_SEED = void 0;
24
+ /** The seed every emulated estate falls back to. */
25
+ exports.DEFAULT_SEED = 'emulated';
26
+ /**
27
+ * The address reduced to what identifies it.
28
+ *
29
+ * Lowercased host, no default port, no trailing slash, no path: `https://Viya.Example.com:443/SASDrive/`
30
+ * and `https://viya.example.com` are one estate, and a path is where a client
31
+ * lands rather than which server it is. A non-default port stays, because two
32
+ * emulators on one machine are two estates.
33
+ */
34
+ const normaliseServerUrl = (url) => {
35
+ if (!url)
36
+ return '';
37
+ const trimmed = url.trim();
38
+ if (!trimmed)
39
+ return '';
40
+ // parsed by hand rather than with `new URL`, because the browser build has no
41
+ // URL global and this module is part of it
42
+ const match = /^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)/i.exec(trimmed);
43
+ if (!match)
44
+ return trimmed.replace(/\/+$/, '').toLowerCase();
45
+ const scheme = (match[1] ?? 'http').toLowerCase();
46
+ let authority = match[2].toLowerCase();
47
+ const credentials = authority.lastIndexOf('@');
48
+ if (credentials >= 0)
49
+ authority = authority.slice(credentials + 1);
50
+ let host = authority;
51
+ let port = '';
52
+ if (authority.startsWith('[')) {
53
+ const close = authority.indexOf(']');
54
+ if (close >= 0) {
55
+ host = authority.slice(0, close + 1);
56
+ if (authority[close + 1] === ':')
57
+ port = authority.slice(close + 2);
58
+ }
59
+ }
60
+ else {
61
+ const colon = authority.lastIndexOf(':');
62
+ if (colon >= 0) {
63
+ host = authority.slice(0, colon);
64
+ port = authority.slice(colon + 1);
65
+ }
66
+ }
67
+ const isDefault = (scheme === 'http' && port === '80') ||
68
+ (scheme === 'https' && port === '443');
69
+ // a non-default port stays: two emulators on one machine are two estates
70
+ return `${scheme}://${host}${port && !isDefault ? `:${port}` : ''}`;
71
+ };
72
+ exports.normaliseServerUrl = normaliseServerUrl;
73
+ /** A 32-bit FNV-1a hash, so one string becomes one number. */
74
+ const hash = (input) => {
75
+ let value = 2166136261;
76
+ for (let index = 0; index < input.length; index++) {
77
+ value ^= input.charCodeAt(index);
78
+ value = Math.imul(value, 16777619) >>> 0;
79
+ }
80
+ return value >>> 0;
81
+ };
82
+ exports.hash = hash;
83
+ /**
84
+ * The number that makes this estate's generated data reproducible.
85
+ *
86
+ * `seed` wins over the address when both are present: it is the override a host
87
+ * reaches for when the address disagrees with the estate, not a second opinion
88
+ * the address gets to overrule.
89
+ */
90
+ const seedOf = (settings = {}) => {
91
+ if (settings.seed !== undefined && settings.seed !== '')
92
+ return (0, exports.hash)(`seed:${settings.seed}`);
93
+ const address = (0, exports.normaliseServerUrl)(settings.serverUrl);
94
+ return (0, exports.hash)(`url:${address || exports.DEFAULT_SEED}`);
95
+ };
96
+ exports.seedOf = seedOf;
97
+ /**
98
+ * A uniform generator over one seed (mulberry32).
99
+ *
100
+ * Every draw advances the same 32-bit state, so a sequence is a function of the
101
+ * seed alone - which is the whole point: the same estate answers the same way,
102
+ * and two estates answer differently.
103
+ */
104
+ const generator = (seed) => {
105
+ let state = seed >>> 0;
106
+ return () => {
107
+ state = (state + 0x6d2b79f5) >>> 0;
108
+ let value = state;
109
+ value = Math.imul(value ^ (value >>> 15), value | 1);
110
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
111
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
112
+ };
113
+ };
114
+ exports.generator = generator;
115
+ /** An integer in `[0, bound)`, drawn from the generator. */
116
+ const drawInt = (next, bound) => Math.floor(next() * bound);
117
+ exports.drawInt = drawInt;
118
+ /** A line from a list, drawn from the generator. */
119
+ const drawFrom = (next, values) => values[(0, exports.drawInt)(next, values.length)];
120
+ exports.drawFrom = drawFrom;