@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
package/build/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @sasjs/api 0.35.0 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
1
+ /* @sasjs/api 0.37.0 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
2
2
  "use strict";
3
3
  var SASjsApi = (() => {
4
4
  var __defProp = Object.defineProperty;
@@ -4350,10 +4350,6 @@ var SASjsApi = (() => {
4350
4350
  reason: "no capture: the authorisation-code step needs a browser; the pass uses the password grant"
4351
4351
  },
4352
4352
  // Compute operations the scripted passes do not reach.
4353
- {
4354
- path: "/compute/sessions/{}/filerefs/_webout/content",
4355
- reason: "no capture: the adapter reads the webout fileref only when a run expects one (`expectWebout`); the execute pass submits a `%put` and reads the log"
4356
- },
4357
4353
  {
4358
4354
  path: "/compute/sessions/{}/variables/{}",
4359
4355
  reason: "no capture: the adapter reads a session variable only to report a submitted job's pid (`printPid`), which the pass does not set"
@@ -4387,8 +4383,27 @@ var SASjsApi = (() => {
4387
4383
  "Access-Control-Expose-Headers": EMULATED_HEADER
4388
4384
  });
4389
4385
 
4386
+ // src/viya/declared.ts
4387
+ var DECLARED = [
4388
+ {
4389
+ id: "GET /compute/sessions/{}/filerefs/_webout/content",
4390
+ method: "GET",
4391
+ path: "/compute/sessions/{}/filerefs/_webout/content",
4392
+ steps: [],
4393
+ // what this emulator answers, not what an estate did: 200 with the webout,
4394
+ // 404 when no program has run in the session
4395
+ statuses: [200, 404],
4396
+ queries: [],
4397
+ request: { queries: [], body: void 0 },
4398
+ // the body is the program's `_webout`, which is whatever the program wrote:
4399
+ // there is no JSON shape to record
4400
+ shape: void 0,
4401
+ 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."
4402
+ }
4403
+ ];
4404
+ var VIYA_OPERATIONS = [...VIYA_TABLE, ...DECLARED];
4405
+
4390
4406
  // src/viya/overlay.ts
4391
- var 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.";
4392
4407
  var NEEDS_AUTH = "The token endpoint is answered by the host that mounts the emulator, which owns the token port.";
4393
4408
  var VIYA_OVERLAY = {
4394
4409
  // answered here
@@ -4400,42 +4415,27 @@ var SASjsApi = (() => {
4400
4415
  "GET /folders/folders/@myRecycleBin": { implemented: true },
4401
4416
  "GET /identities/users/@currentUser": { implemented: true },
4402
4417
  "GET /types/types": { implemented: true },
4403
- // declined: the session and file ports
4404
- "GET /compute/contexts": { implemented: false, reason: NEEDS_RUNTIME },
4405
- "POST /compute/contexts/{}/sessions": {
4406
- implemented: false,
4407
- reason: NEEDS_RUNTIME
4408
- },
4409
- "DELETE /compute/sessions/{}": { implemented: false, reason: NEEDS_RUNTIME },
4410
- "POST /compute/sessions/{}/jobs": {
4411
- implemented: false,
4412
- reason: NEEDS_RUNTIME
4413
- },
4414
- "GET /compute/sessions/{}/jobs/{}": {
4415
- implemented: false,
4416
- reason: NEEDS_RUNTIME
4417
- },
4418
- "GET /compute/sessions/{}/jobs/{}/log/content": {
4419
- implemented: false,
4420
- reason: NEEDS_RUNTIME
4421
- },
4422
- "GET /compute/sessions/{}/jobs/{}/state": {
4423
- implemented: false,
4424
- reason: NEEDS_RUNTIME
4425
- },
4426
- "GET /compute/sessions/{}/state": {
4427
- implemented: false,
4428
- reason: NEEDS_RUNTIME
4429
- },
4430
- "POST /files/files": { implemented: false, reason: NEEDS_RUNTIME },
4431
- "GET /files/files/{}": { implemented: false, reason: NEEDS_RUNTIME },
4432
- "PATCH /files/files/{}": { implemented: false, reason: NEEDS_RUNTIME },
4433
- "GET /files/files/{}/content": { implemented: false, reason: NEEDS_RUNTIME },
4434
- "PUT /files/files/{}/content": { implemented: false, reason: NEEDS_RUNTIME },
4418
+ // answered here: compute
4419
+ "GET /compute/contexts": { implemented: true },
4420
+ "POST /compute/contexts/{}/sessions": { implemented: true },
4421
+ "DELETE /compute/sessions/{}": { implemented: true },
4422
+ "POST /compute/sessions/{}/jobs": { implemented: true },
4423
+ "GET /compute/sessions/{}/jobs/{}": { implemented: true },
4424
+ "GET /compute/sessions/{}/jobs/{}/log/content": { implemented: true },
4425
+ "GET /compute/sessions/{}/jobs/{}/state": { implemented: true },
4426
+ "GET /compute/sessions/{}/state": { implemented: true },
4427
+ // answered here: files
4428
+ "POST /files/files": { implemented: true },
4429
+ "GET /files/files/{}": { implemented: true },
4430
+ "PATCH /files/files/{}": { implemented: true },
4431
+ "GET /files/files/{}/content": { implemented: true },
4432
+ "PUT /files/files/{}/content": { implemented: true },
4435
4433
  // declined: the host owns the token port
4436
- "POST /SASLogon/oauth/token": { implemented: false, reason: NEEDS_AUTH }
4434
+ "POST /SASLogon/oauth/token": { implemented: false, reason: NEEDS_AUTH },
4435
+ // declared, not captured: the webout an application's service returns
4436
+ "GET /compute/sessions/{}/filerefs/_webout/content": { implemented: true }
4437
4437
  };
4438
- var assertOverlayEntries = (overlay, operations = VIYA_TABLE) => {
4438
+ var assertOverlayEntries = (overlay, operations = VIYA_OPERATIONS) => {
4439
4439
  const known2 = new Set(operations.map((operation) => operation.id));
4440
4440
  for (const id of Object.keys(overlay))
4441
4441
  if (!known2.has(id))
@@ -4450,11 +4450,144 @@ var SASjsApi = (() => {
4450
4450
  };
4451
4451
  assertOverlayEntries(VIYA_OVERLAY);
4452
4452
 
4453
- // src/viya/service.ts
4453
+ // src/viya/ports.ts
4454
+ var requireDrive = (services) => services.drive;
4455
+
4456
+ // src/viya/seed.ts
4457
+ var DEFAULT_SEED = "emulated";
4458
+ var normaliseServerUrl = (url) => {
4459
+ if (!url) return "";
4460
+ const trimmed = url.trim();
4461
+ if (!trimmed) return "";
4462
+ const match = /^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)/i.exec(trimmed);
4463
+ if (!match) return trimmed.replace(/\/+$/, "").toLowerCase();
4464
+ const scheme = (match[1] ?? "http").toLowerCase();
4465
+ let authority = match[2].toLowerCase();
4466
+ const credentials = authority.lastIndexOf("@");
4467
+ if (credentials >= 0) authority = authority.slice(credentials + 1);
4468
+ let host = authority;
4469
+ let port = "";
4470
+ if (authority.startsWith("[")) {
4471
+ const close = authority.indexOf("]");
4472
+ if (close >= 0) {
4473
+ host = authority.slice(0, close + 1);
4474
+ if (authority[close + 1] === ":") port = authority.slice(close + 2);
4475
+ }
4476
+ } else {
4477
+ const colon = authority.lastIndexOf(":");
4478
+ if (colon >= 0) {
4479
+ host = authority.slice(0, colon);
4480
+ port = authority.slice(colon + 1);
4481
+ }
4482
+ }
4483
+ const isDefault = scheme === "http" && port === "80" || scheme === "https" && port === "443";
4484
+ return `${scheme}://${host}${port && !isDefault ? `:${port}` : ""}`;
4485
+ };
4486
+ var hash = (input) => {
4487
+ let value = 2166136261;
4488
+ for (let index = 0; index < input.length; index++) {
4489
+ value ^= input.charCodeAt(index);
4490
+ value = Math.imul(value, 16777619) >>> 0;
4491
+ }
4492
+ return value >>> 0;
4493
+ };
4494
+ var seedOf = (settings = {}) => {
4495
+ if (settings.seed !== void 0 && settings.seed !== "")
4496
+ return hash(`seed:${settings.seed}`);
4497
+ const address = normaliseServerUrl(settings.serverUrl);
4498
+ return hash(`url:${address || DEFAULT_SEED}`);
4499
+ };
4500
+ var generator = (seed) => {
4501
+ let state = seed >>> 0;
4502
+ return () => {
4503
+ state = state + 1831565813 >>> 0;
4504
+ let value = state;
4505
+ value = Math.imul(value ^ value >>> 15, value | 1);
4506
+ value ^= value + Math.imul(value ^ value >>> 7, value | 61);
4507
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
4508
+ };
4509
+ };
4510
+ var drawInt = (next, bound) => Math.floor(next() * bound);
4511
+ var drawFrom = (next, values) => values[drawInt(next, values.length)];
4512
+
4513
+ // src/viya/sessions.ts
4514
+ var logFor = (seed, program) => {
4515
+ const code = Array.isArray(program) ? program.join("\n") : program;
4516
+ const next = generator(seed ^ hash(`code:${code}`));
4517
+ const rows = drawInt(next, 900) + 100;
4518
+ const seconds = (drawInt(next, 90) + 10) / 100;
4519
+ const lines = code.split("\n").map((line, index) => `${String(index + 1).padStart(3, " ")} ${line}`);
4520
+ return [
4521
+ "NOTE: Emulated compute engine - this log is generated, not produced by SAS.",
4522
+ "NOTE: No library was touched: the emulated engine has none.",
4523
+ ...lines,
4524
+ `NOTE: The data set WORK.EMULATED has ${rows} observations and 3 variables.`,
4525
+ `NOTE: DATA statement used (Total process time):`,
4526
+ `NOTE: real time ${seconds.toFixed(2)} seconds`,
4527
+ `NOTE: user cpu time ${(seconds / 2).toFixed(2)} seconds`,
4528
+ `NOTE: ${drawFrom(next, ["The emulated run completed.", "Emulation complete - no SAS was executed."])}`
4529
+ ];
4530
+ };
4531
+ var EmulatedEstate = class {
4532
+ constructor(seed) {
4533
+ this.seed = seed;
4534
+ this.sessions = /* @__PURE__ */ new Map();
4535
+ this.created = 0;
4536
+ }
4537
+ /** A new session: deterministic id, no jobs. */
4538
+ create() {
4539
+ const session = {
4540
+ id: `emulated-${this.seed.toString(16)}-ses${String(this.created++).padStart(4, "0")}`,
4541
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4542
+ jobs: /* @__PURE__ */ new Map(),
4543
+ submitted: 0
4544
+ };
4545
+ this.sessions.set(session.id, session);
4546
+ return session;
4547
+ }
4548
+ session(id) {
4549
+ return this.sessions.get(id);
4550
+ }
4551
+ remove(id) {
4552
+ return this.sessions.delete(id);
4553
+ }
4554
+ /** A job accepted into a session, with the log the emulator generated for it. */
4555
+ submit(session, job) {
4556
+ const id = `${session.id}-job${String(session.submitted++).padStart(4, "0")}`;
4557
+ const code = job.code ?? "";
4558
+ const submitted = {
4559
+ id,
4560
+ name: job.name ?? id,
4561
+ // the log is a function of the seed and the program alone, so the same
4562
+ // program answers the same lines whatever session it was submitted in
4563
+ log: logFor(this.seed, code),
4564
+ state: "running",
4565
+ // the real clock, unlike a folder's: a client computes a session's age
4566
+ // from this stamp and expires it, so a fixed instant in the past is a
4567
+ // session that is born expired
4568
+ creationTimeStamp: (/* @__PURE__ */ new Date()).toISOString(),
4569
+ // no completion stamp here: a job is finished when something finished it,
4570
+ // and the handler that knows whether anything will run sets both
4571
+ sessionId: session.id
4572
+ };
4573
+ session.jobs.set(id, submitted);
4574
+ return submitted;
4575
+ }
4576
+ };
4577
+ var estates = /* @__PURE__ */ new Map();
4578
+ var estateFor = (seed) => {
4579
+ const existing = estates.get(seed);
4580
+ if (existing) return existing;
4581
+ const estate = new EmulatedEstate(seed);
4582
+ estates.set(seed, estate);
4583
+ return estate;
4584
+ };
4585
+
4586
+ // src/viya/ids.ts
4454
4587
  var EMULATED_NOW = "2026-01-01T00:00:00.000Z";
4455
4588
  var EMULATED_USER = { id: "emulated-user", name: "Emulated User" };
4456
4589
  var idFor = (path, kind = "folder") => {
4457
- const hash = (input, seed) => {
4590
+ const hash2 = (input, seed) => {
4458
4591
  let value = seed;
4459
4592
  for (let index = 0; index < input.length; index++) {
4460
4593
  value ^= input.charCodeAt(index);
@@ -4462,7 +4595,7 @@ var SASjsApi = (() => {
4462
4595
  }
4463
4596
  return value.toString(16).padStart(8, "0");
4464
4597
  };
4465
- const raw = hash(`${kind}:${path}`, 2166136261) + hash(`${kind}:${path}`, 2246822519) + hash(`${kind}:${path}`, 3266489917) + hash(`${kind}:${path}`, 668265263);
4598
+ const raw = hash2(`${kind}:${path}`, 2166136261) + hash2(`${kind}:${path}`, 2246822519) + hash2(`${kind}:${path}`, 3266489917) + hash2(`${kind}:${path}`, 668265263);
4466
4599
  const hex = raw.slice(0, 32);
4467
4600
  return [
4468
4601
  hex.slice(0, 8),
@@ -4472,7 +4605,432 @@ var SASjsApi = (() => {
4472
4605
  hex.slice(20, 32)
4473
4606
  ].join("-");
4474
4607
  };
4475
- var linksFor = (uri, collection = false) => {
4608
+ var normalisePath = (path) => {
4609
+ const collapsed = `/${path}`.replace(/\/{2,}/g, "/");
4610
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : collapsed;
4611
+ };
4612
+
4613
+ // src/viya/compute.ts
4614
+ var DEFAULT_CONTEXT_NAME = "Emulated Compute Context";
4615
+ var EMULATED_CONTEXT_ID = idFor("emulated-context", "context");
4616
+ var relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: "GET", type }));
4617
+ var linksFor = (uri, type, collection = false, itemType = false) => [
4618
+ // the collection link comes first, because that is the order the capture
4619
+ // recorded and the item shape assertion walks the first element
4620
+ ...collection ? [
4621
+ {
4622
+ href: `${uri}/members`,
4623
+ uri: `${uri}/members`,
4624
+ rel: "members",
4625
+ method: "GET",
4626
+ type,
4627
+ itemType: type
4628
+ }
4629
+ ] : [],
4630
+ {
4631
+ href: uri,
4632
+ uri,
4633
+ rel: "self",
4634
+ method: "GET",
4635
+ type,
4636
+ // the log's capture records itemType on its first link, so it is stamped
4637
+ // there rather than invented as a members link the estate does not have
4638
+ ...itemType ? { itemType: type } : {}
4639
+ }
4640
+ ];
4641
+ var estateOf = (services) => estateFor(seedOf(services.viya));
4642
+ var contextNameFrom = (filter) => {
4643
+ if (!filter) return DEFAULT_CONTEXT_NAME;
4644
+ const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
4645
+ return match?.[1] ?? match?.[2] ?? DEFAULT_CONTEXT_NAME;
4646
+ };
4647
+ var contextBody = (name) => ({
4648
+ id: EMULATED_CONTEXT_ID,
4649
+ name,
4650
+ createdBy: EMULATED_USER.id,
4651
+ version: 2,
4652
+ links: linksFor(
4653
+ `/compute/contexts/${EMULATED_CONTEXT_ID}`,
4654
+ "application/vnd.sas.compute.context"
4655
+ )
4656
+ });
4657
+ var sessionBody = (services, session, autoExecLines) => {
4658
+ const { id } = session;
4659
+ const uri = `/compute/sessions/${id}`;
4660
+ return {
4661
+ id,
4662
+ applicationName: "emulated",
4663
+ owner: EMULATED_USER.id,
4664
+ serverId: idFor(
4665
+ normaliseServerUrl(services.viya?.serverUrl) || "emulated",
4666
+ "server"
4667
+ ),
4668
+ state: "idle",
4669
+ attributes: {
4670
+ homeDirectory: "/tmp/emulated",
4671
+ sessionInactiveTimeout: 3600
4672
+ },
4673
+ environment: { autoExecLines },
4674
+ // the real clock: the adapter computes a session's age from this stamp and
4675
+ // expires it against sessionInactiveTimeout
4676
+ creationTimeStamp: session.createdAt,
4677
+ serviceAPIVersion: 1,
4678
+ sessionConditionCode: 0,
4679
+ stateElapsedTime: 0,
4680
+ version: 2,
4681
+ links: relLinks("application/vnd.sas.compute.session", [
4682
+ ["self", uri],
4683
+ ["state", `${uri}/state`],
4684
+ ["log", `${uri}/log`],
4685
+ ["jobs", `${uri}/jobs`]
4686
+ ])
4687
+ };
4688
+ };
4689
+ var jobBody = (job) => {
4690
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}`;
4691
+ return {
4692
+ id: job.id,
4693
+ name: job.name,
4694
+ sessionId: job.sessionId,
4695
+ state: job.state,
4696
+ creationTimeStamp: job.creationTimeStamp,
4697
+ ...job.completedTimeStamp ? { completedTimeStamp: job.completedTimeStamp } : {},
4698
+ jobConditionCode: 0,
4699
+ stateElapsedTime: 1,
4700
+ listingStatistics: {
4701
+ lineCount: job.log.length,
4702
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
4703
+ },
4704
+ logStatistics: {
4705
+ lineCount: job.log.length,
4706
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
4707
+ },
4708
+ statistics: { systemCpuTime: 0.01, userCpuTime: 0.02 },
4709
+ version: 2,
4710
+ links: relLinks("application/vnd.sas.compute.job", [
4711
+ ["self", uri],
4712
+ ["state", `${uri}/state`],
4713
+ ["log", `${uri}/log`],
4714
+ ["up", `/compute/sessions/${job.sessionId}`]
4715
+ ])
4716
+ };
4717
+ };
4718
+ var sessionOf = (services, id) => {
4719
+ const session = estateOf(services).session(id);
4720
+ if (!session)
4721
+ throw new ApiError(404, `Session with ID '${id}' was not found.`);
4722
+ return session;
4723
+ };
4724
+ var jobOf = (services, sessionId, jobId) => {
4725
+ const job = sessionOf(services, sessionId).jobs.get(jobId);
4726
+ if (!job) throw new ApiError(404, `Job with ID '${jobId}' was not found.`);
4727
+ return job;
4728
+ };
4729
+ var segmentsOf = (params) => params.segments;
4730
+ var COMPUTE_HANDLERS = {
4731
+ "GET /compute/contexts": async ({ request }) => {
4732
+ const limit = Number(request.query?.limit ?? 0) || 0;
4733
+ return {
4734
+ status: 200,
4735
+ body: {
4736
+ accept: "application/json",
4737
+ name: "contexts",
4738
+ start: 0,
4739
+ limit,
4740
+ count: 1,
4741
+ version: 2,
4742
+ items: [contextBody(contextNameFrom(request.query?.filter))],
4743
+ links: linksFor(
4744
+ "/compute/contexts",
4745
+ "application/vnd.sas.compute.context",
4746
+ true
4747
+ )
4748
+ }
4749
+ };
4750
+ },
4751
+ "POST /compute/contexts/{}/sessions": async ({
4752
+ services,
4753
+ params,
4754
+ request
4755
+ }) => {
4756
+ if (params.id !== EMULATED_CONTEXT_ID)
4757
+ throw new ApiError(404, `Context with ID '${params.id}' was not found.`);
4758
+ const body = request.body ?? {};
4759
+ const session = estateOf(services).create();
4760
+ return {
4761
+ status: 201,
4762
+ body: sessionBody(
4763
+ services,
4764
+ session,
4765
+ body.environment?.autoExecLines ?? []
4766
+ )
4767
+ };
4768
+ },
4769
+ "GET /compute/sessions/{}/state": async ({ services, params }) => {
4770
+ sessionOf(services, params.id);
4771
+ return { status: 200, body: "idle" };
4772
+ },
4773
+ "DELETE /compute/sessions/{}": async ({ services, params }) => {
4774
+ sessionOf(services, params.id);
4775
+ estateOf(services).remove(params.id);
4776
+ return { status: 204, body: void 0 };
4777
+ },
4778
+ "POST /compute/sessions/{}/jobs": async ({ services, params, request }) => {
4779
+ const session = sessionOf(services, params.id);
4780
+ const body = request.body ?? {};
4781
+ const job = estateOf(services).submit(session, body);
4782
+ const execute = services.viya?.execute;
4783
+ if (!execute) {
4784
+ job.state = "completed";
4785
+ job.completedTimeStamp = (/* @__PURE__ */ new Date()).toISOString();
4786
+ return { status: 201, body: jobBody(job) };
4787
+ }
4788
+ job.state = "running";
4789
+ job.log = [];
4790
+ void execute({
4791
+ program: body.code ?? "",
4792
+ variables: body.variables,
4793
+ name: body.name,
4794
+ sessionId: session.id
4795
+ }).then((ran) => {
4796
+ job.log = ran.log.split("\n");
4797
+ job.state = ran.state ?? "completed";
4798
+ if (ran.webout !== void 0) job.webout = ran.webout;
4799
+ job.completedTimeStamp = (/* @__PURE__ */ new Date()).toISOString();
4800
+ }).catch((error) => {
4801
+ job.state = "failed";
4802
+ job.log = [`ERROR: ${error.message}`];
4803
+ job.completedTimeStamp = (/* @__PURE__ */ new Date()).toISOString();
4804
+ });
4805
+ return { status: 201, body: jobBody(job) };
4806
+ },
4807
+ "GET /compute/sessions/{}/filerefs/_webout/content": async ({
4808
+ services,
4809
+ params
4810
+ }) => {
4811
+ const session = sessionOf(services, params.id);
4812
+ const last = [...session.jobs.values()].pop();
4813
+ if (!last)
4814
+ throw new ApiError(
4815
+ 404,
4816
+ "This session has no `_webout` yet: nothing has run in it."
4817
+ );
4818
+ if (last.webout === void 0)
4819
+ throw new ApiError(
4820
+ 404,
4821
+ last.state === "running" ? `This session has no \`_webout\` yet: job '${last.id}' has not finished.` : services.viya?.execute ? `This session has no \`_webout\`: job '${last.id}' ran and produced none.` : `This session has no \`_webout\`: the host supplied no engine, so no program has run.`
4822
+ );
4823
+ return {
4824
+ status: 200,
4825
+ contents: last.webout,
4826
+ headers: { "content-type": "text/plain" }
4827
+ };
4828
+ },
4829
+ "GET /compute/sessions/{}/jobs/{}": async ({ services, params }) => {
4830
+ const [sessionId, jobId] = segmentsOf(params);
4831
+ return { status: 200, body: jobBody(jobOf(services, sessionId, jobId)) };
4832
+ },
4833
+ "GET /compute/sessions/{}/jobs/{}/state": async ({ services, params }) => {
4834
+ const [sessionId, jobId] = segmentsOf(params);
4835
+ return {
4836
+ status: 200,
4837
+ body: jobOf(services, sessionId, jobId).state
4838
+ };
4839
+ },
4840
+ "GET /compute/sessions/{}/jobs/{}/log/content": async ({
4841
+ services,
4842
+ params,
4843
+ request
4844
+ }) => {
4845
+ const [sessionId, jobId] = segmentsOf(params);
4846
+ const job = jobOf(services, sessionId, jobId);
4847
+ const start = Number(request.query?.start ?? 0) || 0;
4848
+ const limit = Number(request.query?.limit ?? 0) || 0;
4849
+ const lines = job.log.slice(start, limit ? start + limit : void 0);
4850
+ return {
4851
+ status: 200,
4852
+ body: {
4853
+ accept: "application/json",
4854
+ name: "content",
4855
+ start,
4856
+ limit: limit || lines.length,
4857
+ count: job.log.length,
4858
+ version: 2,
4859
+ items: lines.map((line) => ({ line, type: "NOTE", version: 2 })),
4860
+ links: linksFor(
4861
+ `/compute/sessions/${job.sessionId}/jobs/${job.id}/log`,
4862
+ "application/vnd.sas.compute.job.log",
4863
+ false,
4864
+ true
4865
+ )
4866
+ }
4867
+ };
4868
+ }
4869
+ };
4870
+
4871
+ // src/viya/files.ts
4872
+ var contentTypeOf = (name) => {
4873
+ if (/\.sas$/i.test(name)) return "text/plain";
4874
+ if (/\.(json)$/i.test(name)) return "application/json";
4875
+ if (/\.(csv|txt|log)$/i.test(name)) return "text/plain";
4876
+ if (/\.(html?)$/i.test(name)) return "text/html";
4877
+ if (/\.(png)$/i.test(name)) return "image/png";
4878
+ if (/\.(jpe?g)$/i.test(name)) return "image/jpeg";
4879
+ return "application/octet-stream";
4880
+ };
4881
+ var fileBody = (file) => {
4882
+ const id = idFor(file.path, "file");
4883
+ const uri = `/files/files/${id}`;
4884
+ const contentType = contentTypeOf(file.name);
4885
+ return {
4886
+ id,
4887
+ name: file.name,
4888
+ contentType,
4889
+ contentDisposition: `attachment; filename="${file.name}"`,
4890
+ encoding: "UTF-8",
4891
+ size: file.size,
4892
+ fileStatus: "complete",
4893
+ fileVersion: 1,
4894
+ version: 2,
4895
+ typeDefName: "file",
4896
+ createdBy: EMULATED_USER.id,
4897
+ modifiedBy: EMULATED_USER.id,
4898
+ creationTimeStamp: EMULATED_NOW,
4899
+ modifiedTimeStamp: EMULATED_NOW,
4900
+ quarantine: false,
4901
+ searchable: true,
4902
+ virusDetected: false,
4903
+ urlDetected: false,
4904
+ properties: {
4905
+ "content.download": "true",
4906
+ "content.openInBrowser": "true",
4907
+ "content.preview": "false",
4908
+ sasIconKey: "file",
4909
+ typeRegistrant: EMULATED_USER.id
4910
+ },
4911
+ links: [
4912
+ {
4913
+ href: uri,
4914
+ uri,
4915
+ rel: "self",
4916
+ method: "GET",
4917
+ type: "application/vnd.sas.file"
4918
+ },
4919
+ {
4920
+ href: `${uri}/content`,
4921
+ uri: `${uri}/content`,
4922
+ rel: "content",
4923
+ method: "GET",
4924
+ type: "application/vnd.sas.file.content"
4925
+ }
4926
+ ]
4927
+ };
4928
+ };
4929
+ var utf8Length2 = (text2) => {
4930
+ let bytes3 = 0;
4931
+ for (const character of text2) {
4932
+ const point = character.codePointAt(0);
4933
+ bytes3 += point < 128 ? 1 : point < 2048 ? 2 : point < 65536 ? 3 : 4;
4934
+ }
4935
+ return bytes3;
4936
+ };
4937
+ var sizeOf = (contents) => typeof contents === "string" ? utf8Length2(contents) : contents.byteLength;
4938
+ var filesIn = async (drive) => {
4939
+ const walk2 = (node, found) => {
4940
+ if (!node.isFolder)
4941
+ found.push({ name: node.name, path: node.relativePath, size: 0 });
4942
+ for (const child of node.children) walk2(child, found);
4943
+ return found;
4944
+ };
4945
+ return walk2((await drive.tree("/")).tree, []);
4946
+ };
4947
+ var pathForFileId = async (drive, id) => {
4948
+ const file = (await filesIn(drive)).find(
4949
+ (candidate) => idFor(candidate.path, "file") === id
4950
+ );
4951
+ if (!file) throw new ApiError(404, `File with ID '${id}' was not found.`);
4952
+ return file.path;
4953
+ };
4954
+ var bodyOf = async (drive, path) => {
4955
+ const read = await drive.read(path);
4956
+ return {
4957
+ name: path.split("/").pop(),
4958
+ path,
4959
+ size: sizeOf(read.contents)
4960
+ };
4961
+ };
4962
+ var parentOf = async (drive, uri) => {
4963
+ if (!uri) return "/";
4964
+ const id = uri.split("/").pop();
4965
+ const tree = await drive.tree("/");
4966
+ const walk2 = (node) => {
4967
+ if (node.isFolder && idFor(node.relativePath, "folder") === id)
4968
+ return node.relativePath;
4969
+ for (const child of node.children) {
4970
+ const hit = walk2(child);
4971
+ if (hit !== void 0) return hit;
4972
+ }
4973
+ return void 0;
4974
+ };
4975
+ const found = walk2(tree.tree);
4976
+ if (found === void 0)
4977
+ throw new ApiError(404, `Folder with ID '${id}' was not found.`);
4978
+ return found;
4979
+ };
4980
+ var FILE_HANDLERS = {
4981
+ "POST /files/files": async ({ services, request }) => {
4982
+ const drive = requireDrive(services);
4983
+ const upload = request.file;
4984
+ if (!upload?.name)
4985
+ throw new ApiError(400, "A file named `file` is required.");
4986
+ const parent = await parentOf(drive, request.query?.parentFolderUri);
4987
+ const path = `${parent}/${upload.name}`.replace(/\/{2,}/g, "/");
4988
+ await drive.save(path, upload.contents);
4989
+ return { status: 201, body: fileBody(await bodyOf(drive, path)) };
4990
+ },
4991
+ "GET /files/files/{}": async ({ services, params }) => {
4992
+ const drive = requireDrive(services);
4993
+ const path = await pathForFileId(drive, params.id);
4994
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
4995
+ },
4996
+ "PATCH /files/files/{}": async ({ services, params, request }) => {
4997
+ const drive = requireDrive(services);
4998
+ const path = await pathForFileId(drive, params.id);
4999
+ const body = request.body ?? {};
5000
+ const name = body.name ?? path.split("/").pop();
5001
+ const target = `${path.split("/").slice(0, -1).join("/")}/${name}`.replace(
5002
+ /\/{2,}/g,
5003
+ "/"
5004
+ );
5005
+ if (target !== path) await drive.rename(path, target);
5006
+ return { status: 200, body: fileBody(await bodyOf(drive, target)) };
5007
+ },
5008
+ "GET /files/files/{}/content": async ({ services, params }) => {
5009
+ const drive = requireDrive(services);
5010
+ const path = await pathForFileId(drive, params.id);
5011
+ const read = await drive.read(path);
5012
+ return {
5013
+ status: 200,
5014
+ contents: read.contents,
5015
+ headers: {
5016
+ "content-type": contentTypeOf(path.split("/").pop())
5017
+ }
5018
+ };
5019
+ },
5020
+ "PUT /files/files/{}/content": async ({ services, params, request }) => {
5021
+ const drive = requireDrive(services);
5022
+ const path = await pathForFileId(drive, params.id);
5023
+ const body = request.body;
5024
+ const contents = request.file?.contents ?? (typeof body === "string" ? body : body?.contents);
5025
+ if (contents === void 0 || contents === null)
5026
+ throw new ApiError(400, "File content is required.");
5027
+ await drive.update(path, contents);
5028
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
5029
+ }
5030
+ };
5031
+
5032
+ // src/viya/service.ts
5033
+ var linksFor2 = (uri, collection = false) => {
4476
5034
  const self = {
4477
5035
  href: uri,
4478
5036
  uri,
@@ -4507,7 +5065,7 @@ var SASjsApi = (() => {
4507
5065
  modifiedTimeStamp: EMULATED_NOW,
4508
5066
  memberCount: listing.files.length + listing.folders.length,
4509
5067
  parentFolderUri: `/folders/folders/${idFor(parent)}`,
4510
- links: linksFor(`/folders/folders/${id}`)
5068
+ links: linksFor2(`/folders/folders/${id}`)
4511
5069
  };
4512
5070
  };
4513
5071
  var recycleBin = () => {
@@ -4526,21 +5084,13 @@ var SASjsApi = (() => {
4526
5084
  memberCount: 0,
4527
5085
  parentFolderUri: "",
4528
5086
  properties: { allowMove: "false" },
4529
- links: linksFor(`/folders/folders/${id}`)
5087
+ links: linksFor2(`/folders/folders/${id}`)
4530
5088
  };
4531
5089
  };
4532
- var requireDrive = (services) => {
4533
- if (!services.drive)
4534
- throw new ApiError(
4535
- 501,
4536
- "This host has no drive, so it cannot answer a folder operation."
4537
- );
4538
- return services.drive;
4539
- };
4540
5090
  var pathFromQuery = (request) => {
4541
5091
  const path = request.query?.path;
4542
5092
  if (!path) throw new ApiError(400, "The path parameter is required.");
4543
- return path;
5093
+ return normalisePath(path);
4544
5094
  };
4545
5095
  var RECYCLE_BIN_ALIAS = "/folders/folders/@myRecycleBin";
4546
5096
  var isRecycleBin = (uri) => !!uri && (uri === RECYCLE_BIN_ALIAS || uri.endsWith(`/${idFor("@myRecycleBin")}`));
@@ -4636,7 +5186,7 @@ var SASjsApi = (() => {
4636
5186
  count: 0,
4637
5187
  version: 2,
4638
5188
  items: [],
4639
- links: linksFor(`/folders/folders/${idFor("@myRecycleBin")}`, true)
5189
+ links: linksFor2(`/folders/folders/${idFor("@myRecycleBin")}`, true)
4640
5190
  }
4641
5191
  };
4642
5192
  const path = await pathForId(drive, params.id);
@@ -4653,7 +5203,7 @@ var SASjsApi = (() => {
4653
5203
  modifiedTimeStamp: EMULATED_NOW,
4654
5204
  parentFolderUri: `/folders/folders/${idFor(path)}`,
4655
5205
  uri: `${path}/${name}`.replace(/\/{2,}/g, "/"),
4656
- links: linksFor(
5206
+ links: linksFor2(
4657
5207
  `/folders/folders/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"))}`
4658
5208
  )
4659
5209
  })),
@@ -4670,7 +5220,7 @@ var SASjsApi = (() => {
4670
5220
  parentFolderUri: `/folders/folders/${idFor(path)}`,
4671
5221
  added: EMULATED_NOW,
4672
5222
  uri: `${path}/${name}`.replace(/\/{2,}/g, "/"),
4673
- links: linksFor(
5223
+ links: linksFor2(
4674
5224
  `/files/files/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"), "file")}`
4675
5225
  )
4676
5226
  }))
@@ -4686,7 +5236,7 @@ var SASjsApi = (() => {
4686
5236
  count: page.length,
4687
5237
  version: 2,
4688
5238
  items: page,
4689
- links: linksFor(`/folders/folders/${idFor(path)}`, true)
5239
+ links: linksFor2(`/folders/folders/${idFor(path)}`, true)
4690
5240
  }
4691
5241
  };
4692
5242
  },
@@ -4696,7 +5246,7 @@ var SASjsApi = (() => {
4696
5246
  if (!body.name) throw new ApiError(400, "A folder name is required.");
4697
5247
  const parentUri = request.query?.parentFolderUri ?? body.parentFolderUri;
4698
5248
  const parent = parentUri ? await pathForId(drive, String(parentUri).split("/").pop()) : "/";
4699
- const path = `${parent}/${body.name}`.replace(/\/{2,}/g, "/");
5249
+ const path = normalisePath(`${parent}/${body.name}`);
4700
5250
  await drive.mkdir(path);
4701
5251
  return { status: 201, body: await folderBody(drive, path) };
4702
5252
  },
@@ -4719,15 +5269,17 @@ var SASjsApi = (() => {
4719
5269
  drive,
4720
5270
  body.parentFolderUri.split("/").pop()
4721
5271
  );
4722
- const target = `${parent}/${name}`.replace(/\/{2,}/g, "/");
5272
+ const target = normalisePath(`${parent}/${name}`);
4723
5273
  if (target !== path) await drive.rename(path, target);
4724
5274
  return { status: 200, body: await folderBody(drive, target) };
4725
- }
5275
+ },
5276
+ ...COMPUTE_HANDLERS,
5277
+ ...FILE_HANDLERS
4726
5278
  };
4727
5279
 
4728
5280
  // src/viya/dispatch.ts
4729
5281
  var escape2 = (segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4730
- var compiled2 = VIYA_TABLE.filter(
5282
+ var compiled2 = VIYA_OPERATIONS.filter(
4731
5283
  (operation) => operation.path.includes("{}")
4732
5284
  ).map((operation) => ({
4733
5285
  operation,
@@ -4738,7 +5290,7 @@ var SASjsApi = (() => {
4738
5290
  )
4739
5291
  }));
4740
5292
  var exact2 = /* @__PURE__ */ new Map();
4741
- for (const operation of VIYA_TABLE)
5293
+ for (const operation of VIYA_OPERATIONS)
4742
5294
  if (!operation.path.includes("{}"))
4743
5295
  exact2.set(`${operation.method} ${operation.path}`.toLowerCase(), operation);
4744
5296
  var findViyaOperation = (method, path) => {