@sasjs/api 0.23.1 → 0.25.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 (55) hide show
  1. package/README.md +10 -0
  2. package/build/browser.js +695 -101
  3. package/build/cjs/appstream/bundle.js +124 -0
  4. package/build/cjs/appstream/identity.js +69 -0
  5. package/build/cjs/appstream/service.js +226 -0
  6. package/build/cjs/appstream/store.js +69 -0
  7. package/build/cjs/appstream/web.js +248 -0
  8. package/build/cjs/corpus/deploy.js +112 -29
  9. package/build/cjs/corpus/runner.js +30 -18
  10. package/build/cjs/drive/deploy.js +20 -4
  11. package/build/cjs/drive/service.js +2 -2
  12. package/build/cjs/host/dispatch.js +38 -9
  13. package/build/cjs/index.js +25 -4
  14. package/build/cjs/routes/generated.js +2 -8
  15. package/build/cjs/routes/overlay.js +2 -2
  16. package/build/esm/appstream/bundle.d.ts +46 -0
  17. package/build/esm/appstream/bundle.d.ts.map +1 -0
  18. package/build/esm/appstream/bundle.js +118 -0
  19. package/build/esm/appstream/identity.d.ts +27 -0
  20. package/build/esm/appstream/identity.d.ts.map +1 -0
  21. package/build/esm/appstream/identity.js +63 -0
  22. package/build/esm/appstream/service.d.ts +96 -0
  23. package/build/esm/appstream/service.d.ts.map +1 -0
  24. package/build/esm/appstream/service.js +218 -0
  25. package/build/esm/appstream/store.d.ts +6 -0
  26. package/build/esm/appstream/store.d.ts.map +1 -0
  27. package/build/esm/appstream/store.js +65 -0
  28. package/build/esm/appstream/web.d.ts +74 -0
  29. package/build/esm/appstream/web.d.ts.map +1 -0
  30. package/build/esm/appstream/web.js +241 -0
  31. package/build/esm/corpus/deploy.d.ts +5 -5
  32. package/build/esm/corpus/deploy.d.ts.map +1 -1
  33. package/build/esm/corpus/deploy.js +112 -29
  34. package/build/esm/corpus/runner.d.ts.map +1 -1
  35. package/build/esm/corpus/runner.js +14 -2
  36. package/build/esm/drive/deploy.d.ts +41 -2
  37. package/build/esm/drive/deploy.d.ts.map +1 -1
  38. package/build/esm/drive/deploy.js +20 -4
  39. package/build/esm/drive/service.d.ts +2 -1
  40. package/build/esm/drive/service.d.ts.map +1 -1
  41. package/build/esm/drive/service.js +2 -2
  42. package/build/esm/host/dispatch.d.ts +5 -4
  43. package/build/esm/host/dispatch.d.ts.map +1 -1
  44. package/build/esm/host/dispatch.js +38 -9
  45. package/build/esm/index.d.ts +9 -3
  46. package/build/esm/index.d.ts.map +1 -1
  47. package/build/esm/index.js +5 -1
  48. package/build/esm/routes/generated.d.ts.map +1 -1
  49. package/build/esm/routes/generated.js +2 -8
  50. package/build/esm/routes/overlay.js +2 -2
  51. package/package.json +5 -4
  52. package/build/cjs/drive/registry.js +0 -38
  53. package/build/esm/drive/registry.d.ts +0 -52
  54. package/build/esm/drive/registry.d.ts.map +0 -1
  55. package/build/esm/drive/registry.js +0 -33
package/build/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @sasjs/api 0.23.1 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
1
+ /* @sasjs/api 0.25.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;
@@ -25,12 +25,15 @@ var SASjsApi = (() => {
25
25
  ADMIN_CORPUS: () => ADMIN_CORPUS,
26
26
  ADMIN_SIGNED_IN: () => ADMIN_SIGNED_IN,
27
27
  ALWAYS_VISIBLE_ROUTES: () => ALWAYS_VISIBLE_ROUTES,
28
+ APP_MANIFEST: () => APP_MANIFEST,
29
+ APP_STREAM_INDEX: () => APP_STREAM_INDEX,
28
30
  AUTH_CONFIG_CORPUS: () => AUTH_CONFIG_CORPUS,
29
31
  ApiError: () => ApiError,
30
32
  BROWSER_INFO: () => BROWSER_INFO,
31
33
  BUNDLE_NAME: () => BUNDLE_NAME,
32
34
  CODE_CORPUS: () => CODE_CORPUS,
33
35
  CODE_DEBUG: () => CODE_DEBUG,
36
+ DEFAULT_APP_PATH: () => DEFAULT_APP_PATH,
34
37
  DEFAULT_GRANTABLE_ROUTES: () => DEFAULT_GRANTABLE_ROUTES,
35
38
  DEFAULT_IDENTITY: () => DEFAULT_IDENTITY,
36
39
  DEFAULT_LOG_LINES: () => DEFAULT_LOG_LINES,
@@ -48,11 +51,12 @@ var SASjsApi = (() => {
48
51
  IDENTITY_FORMAT: () => IDENTITY_FORMAT,
49
52
  INFO_CORPUS: () => INFO_CORPUS,
50
53
  MAX_LOG_LINES: () => MAX_LOG_LINES,
51
- MemoryAppStreamRegistry: () => MemoryAppStreamRegistry,
54
+ MemoryAppStreamStore: () => MemoryAppStreamStore,
52
55
  MemoryDriveStore: () => MemoryDriveStore,
53
56
  MemoryIdentityStore: () => MemoryIdentityStore,
54
57
  MemorySessionHost: () => MemorySessionHost,
55
58
  MemorySessionRunner: () => MemorySessionRunner,
59
+ NO_SUCH_APP: () => NO_SUCH_APP,
56
60
  NO_WEB_BUILD: () => NO_WEB_BUILD,
57
61
  OVERLAY: () => OVERLAY,
58
62
  PROVIDER_MANAGED: () => PROVIDER_MANAGED,
@@ -63,12 +67,18 @@ var SASjsApi = (() => {
63
67
  STATIC_AUTHORIZED_ROUTES: () => STATIC_AUTHORIZED_ROUTES,
64
68
  TAG_CAPABILITIES: () => TAG_CAPABILITIES,
65
69
  TOP_LEVEL_ROUTES: () => TOP_LEVEL_ROUTES,
70
+ appSummary: () => appSummary,
66
71
  basename: () => basename,
72
+ cacheControlFor: () => cacheControlFor,
67
73
  checkDeployTree: () => checkDeployTree,
68
74
  checkLogFileName: () => checkLogFileName,
75
+ contentTypeFor: () => contentTypeFor,
69
76
  createAdminService: () => createAdminService,
77
+ createAppStreamService: () => createAppStreamService,
78
+ createAppStreamWebService: () => createAppStreamWebService,
70
79
  createAuthConfigService: () => createAuthConfigService,
71
80
  createDirectoryService: () => createDirectoryService,
81
+ createDriveAppStreamStore: () => createDriveAppStreamStore,
72
82
  createDriveService: () => createDriveService,
73
83
  createHomeService: () => createHomeService,
74
84
  createIdentityService: () => createIdentityService,
@@ -77,29 +87,36 @@ var SASjsApi = (() => {
77
87
  createRuntimeService: () => createRuntimeService,
78
88
  createSessionService: () => createSessionService,
79
89
  decodeBase64: () => decodeBase64,
90
+ defaultAppName: () => defaultAppName,
80
91
  deployTree: () => deployTree,
81
92
  dirname: () => dirname,
82
93
  dispatch: () => dispatch,
94
+ escapeHtml: () => escapeHtml,
83
95
  findRoute: () => findRoute,
84
96
  hasBlockedExtension: () => hasBlockedExtension,
85
97
  isApiError: () => isApiError,
98
+ isAppId: () => isAppId,
86
99
  isDeployTree: () => isDeployTree,
87
100
  isRoot: () => isRoot,
88
101
  isRouteGranted: () => isRouteGranted,
89
102
  logLines: () => logLines,
90
103
  measureDeployTree: () => measureDeployTree,
104
+ newAppId: () => newAppId,
105
+ normaliseAppLoc: () => normaliseAppLoc,
91
106
  normaliseAuthConfig: () => normaliseAuthConfig,
92
107
  normaliseDiagnostics: () => normaliseDiagnostics,
93
108
  normaliseDrivePath: () => normaliseDrivePath,
94
109
  normaliseInfo: () => normaliseInfo,
95
110
  normaliseLogFiles: () => normaliseLogFiles,
111
+ parseAppManifest: () => parseAppManifest,
96
112
  parseIdentity: () => parseIdentity,
113
+ publishRequestFor: () => publishRequestFor,
97
114
  routeById: () => routeById,
98
115
  runCase: () => runCase,
99
116
  sanitiseDisplayName: () => sanitiseDisplayName,
100
117
  servicesFor: () => servicesFor,
118
+ splitAppBundle: () => splitAppBundle,
101
119
  topLevelRouteFor: () => topLevelRouteFor,
102
- unpublishAppStream: () => unpublishAppStream,
103
120
  withBundleVersion: () => withBundleVersion
104
121
  });
105
122
 
@@ -120,9 +137,9 @@ var SASjsApi = (() => {
120
137
  var BLOCKED_EXTENSION = /\.(exe|sh|htaccess)$/i;
121
138
  var hasBlockedExtension = (path) => BLOCKED_EXTENSION.test(path);
122
139
  var normaliseDrivePath = (input) => {
123
- const given = typeof input === "string" ? input : "";
140
+ const given2 = typeof input === "string" ? input : "";
124
141
  const segments = [];
125
- for (const segment of given.replace(/\\/g, "/").split("/")) {
142
+ for (const segment of given2.replace(/\\/g, "/").split("/")) {
126
143
  if (!segment || segment === ".") continue;
127
144
  if (segment === "..") {
128
145
  if (!segments.length) return null;
@@ -191,7 +208,7 @@ var SASjsApi = (() => {
191
208
  return bytes3;
192
209
  };
193
210
  var memberName = (member) => member.type === "service" ? `${member.name}.sas` : member.name;
194
- var memberBytes = (member) => member.type === "file" ? base64Length(member.code) : utf8Length(member.code);
211
+ var memberBytes = (member) => member.type === "file" && member.encoding === "base64" ? base64Length(member.code) : utf8Length(member.code);
195
212
  var MEGABYTE = 1024 * 1024;
196
213
  var describeSize = (bytes3) => bytes3 < MEGABYTE ? `${bytes3} bytes` : `${Math.ceil(bytes3 / MEGABYTE * 10) / 10} MB`;
197
214
  var describeLimit = (bytes3) => bytes3 < MEGABYTE ? `${bytes3} bytes` : `${Math.round(bytes3 / MEGABYTE * 10) / 10} MB`;
@@ -276,11 +293,13 @@ var SASjsApi = (() => {
276
293
  if (typeof member.name !== "string") return false;
277
294
  if (member.type === "folder")
278
295
  return Array.isArray(member.members) && member.members.every(isDeployMember);
279
- if (member.type === "service" || member.type === "file")
280
- return typeof member.code === "string";
296
+ if (member.type === "service") return typeof member.code === "string";
297
+ if (member.type === "file")
298
+ return typeof member.code === "string" && (member.encoding === void 0 || member.encoding === "utf8" || member.encoding === "base64");
281
299
  return false;
282
300
  };
283
- var deployTree = async (store, appLoc, tree, limits = DEPLOY_LIMITS) => {
301
+ var deployTree = async (store, appLoc, tree, options = {}) => {
302
+ const limits = options.limits ?? DEPLOY_LIMITS;
284
303
  if (!isDeployTree(tree))
285
304
  throw new ApiError(400, "Provided not supported data format.", {
286
305
  status: "failure",
@@ -299,6 +318,8 @@ var SASjsApi = (() => {
299
318
  message: refusal.message
300
319
  });
301
320
  try {
321
+ if (options.replace && await store.exists(root)) await store.remove(root);
322
+ await store.mkdirp(root);
302
323
  await writeMembers(store, tree.members, root);
303
324
  } catch {
304
325
  throw new ApiError(500, "Deployment failed!", {
@@ -317,7 +338,7 @@ var SASjsApi = (() => {
317
338
  }
318
339
  await store.write(
319
340
  path,
320
- member.type === "file" ? decodeBase64(member.code) : member.code
341
+ member.type === "file" && member.encoding === "base64" ? decodeBase64(member.code) : member.code
321
342
  );
322
343
  }
323
344
  };
@@ -365,9 +386,9 @@ var SASjsApi = (() => {
365
386
  };
366
387
  };
367
388
  return {
368
- async list(given) {
389
+ async list(given2) {
369
390
  const path = folderPath(
370
- given === void 0 ? "" : given,
391
+ given2 === void 0 ? "" : given2,
371
392
  "Can't get folder outside drive."
372
393
  );
373
394
  if (!await store.exists(path))
@@ -380,37 +401,37 @@ var SASjsApi = (() => {
380
401
  folders: [...listing.folders].sort()
381
402
  };
382
403
  },
383
- async read(given) {
384
- const path = filePath(given, "Can't get file outside drive.");
404
+ async read(given2) {
405
+ const path = filePath(given2, "Can't get file outside drive.");
385
406
  if (!await store.exists(path))
386
407
  throw new ApiError(404, `File doesn't exist.`);
387
408
  const contents = await store.read(path);
388
409
  return { contents, binary: typeof contents !== "string" };
389
410
  },
390
- async save(given, contents) {
391
- const path = filePath(given, "Can't put file outside drive.");
411
+ async save(given2, contents) {
412
+ const path = filePath(given2, "Can't put file outside drive.");
392
413
  if (await store.exists(path))
393
414
  throw new ApiError(409, "File already exists.");
394
415
  await store.mkdirp(dirname(path));
395
416
  await store.write(path, contents);
396
417
  return { status: "success" };
397
418
  },
398
- async update(given, contents) {
399
- const path = filePath(given, "Can't modify file outside drive.");
419
+ async update(given2, contents) {
420
+ const path = filePath(given2, "Can't modify file outside drive.");
400
421
  if (!await store.exists(path))
401
422
  throw new ApiError(404, `File doesn't exist.`);
402
423
  await store.write(path, contents);
403
424
  return { status: "success" };
404
425
  },
405
- async remove(given) {
406
- const path = filePath(given, "Can't delete file outside drive.");
426
+ async remove(given2) {
427
+ const path = filePath(given2, "Can't delete file outside drive.");
407
428
  if (!await store.exists(path))
408
429
  throw new ApiError(404, `File doesn't exist.`);
409
430
  await store.remove(path);
410
431
  return { status: "success" };
411
432
  },
412
- async mkdir(given) {
413
- const path = folderPath(given, "Can't put folder outside drive.");
433
+ async mkdir(given2) {
434
+ const path = folderPath(given2, "Can't put folder outside drive.");
414
435
  if (isRoot(path))
415
436
  throw new ApiError(400, "Can't put folder outside drive.");
416
437
  if (await store.exists(path))
@@ -418,8 +439,8 @@ var SASjsApi = (() => {
418
439
  await store.mkdirp(path);
419
440
  return { status: "success" };
420
441
  },
421
- async rmdir(given) {
422
- const path = folderPath(given, "Can't delete folder outside drive.");
442
+ async rmdir(given2) {
443
+ const path = folderPath(given2, "Can't delete folder outside drive.");
423
444
  if (isRoot(path))
424
445
  throw new ApiError(400, "Can't delete folder outside drive.");
425
446
  if (!await store.exists(path) || !(await store.stat(path)).directory)
@@ -451,9 +472,9 @@ var SASjsApi = (() => {
451
472
  }
452
473
  throw new ApiError(404, "No file/folder found for provided path.");
453
474
  },
454
- async tree(given) {
475
+ async tree(given2) {
455
476
  const path = folderPath(
456
- given === void 0 ? "" : given,
477
+ given2 === void 0 ? "" : given2,
457
478
  "Can't get folder outside drive."
458
479
  );
459
480
  if (!await store.exists(path))
@@ -462,8 +483,8 @@ var SASjsApi = (() => {
462
483
  if (!stat.directory) throw new ApiError(400, "Not a Folder.");
463
484
  return { status: "success", tree: await treeOf(path) };
464
485
  },
465
- async deploy(appLoc, tree) {
466
- await deployTree(store, appLoc, tree);
486
+ async deploy(appLoc, tree, options) {
487
+ await deployTree(store, appLoc, tree, options);
467
488
  return { status: "success" };
468
489
  }
469
490
  };
@@ -1107,13 +1128,7 @@ var SASjsApi = (() => {
1107
1128
  summary: "Remove an app stream entry",
1108
1129
  params: [
1109
1130
  {
1110
- name: "appLoc",
1111
- in: "body",
1112
- required: true,
1113
- type: "string"
1114
- },
1115
- {
1116
- name: "streamServiceName",
1131
+ name: "id",
1117
1132
  in: "body",
1118
1133
  required: true,
1119
1134
  type: "string"
@@ -1131,7 +1146,7 @@ var SASjsApi = (() => {
1131
1146
  },
1132
1147
  {
1133
1148
  status: 404,
1134
- description: "No app is published at that folder"
1149
+ description: "No app is published with that id"
1135
1150
  }
1136
1151
  ]
1137
1152
  },
@@ -2887,8 +2902,8 @@ var SASjsApi = (() => {
2887
2902
  }
2888
2903
  },
2889
2904
  "POST /SASjsApi/drive/deploy/upload": { implemented: true },
2890
- // `404` is a pair - the registry name and the appLoc it was published from -
2891
- // that matches no entry, and the drive's content is deliberately left alone.
2905
+ // `404` is an id the index does not hold - the id is the app, and its label and
2906
+ // folder are not handles - and the drive's content is deliberately left alone.
2892
2907
  "DELETE /SASjsApi/drive/deploy": { implemented: true },
2893
2908
  // Group - members and the groups themselves
2894
2909
  "GET /SASjsApi/group": { implemented: true },
@@ -3068,24 +3083,273 @@ var SASjsApi = (() => {
3068
3083
  return void 0;
3069
3084
  };
3070
3085
 
3071
- // src/drive/registry.ts
3072
- var unpublishAppStream = async (registry, body) => {
3073
- if (!body?.streamServiceName)
3074
- throw new ApiError(400, '"streamServiceName" is required');
3075
- if (!body.appLoc) throw new ApiError(400, '"appLoc" is required');
3076
- if (!await registry.unpublish(body.appLoc))
3077
- throw new ApiError(404, "No app is published at that folder.");
3078
- return { status: "success" };
3086
+ // src/appstream/identity.ts
3087
+ var normaliseAppLoc = (appLoc) => {
3088
+ if (typeof appLoc !== "string" || appLoc === "")
3089
+ throw new Error(
3090
+ `App location must be a non-empty string, got ${JSON.stringify(appLoc)}.`
3091
+ );
3092
+ const normalised = normaliseDrivePath(appLoc);
3093
+ if (normalised === null)
3094
+ throw new ApiError(400, "appLoc cannot be outside drive.");
3095
+ return normalised;
3096
+ };
3097
+ var newAppId = () => {
3098
+ const webCrypto = globalThis.crypto;
3099
+ if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
3100
+ if (typeof webCrypto?.getRandomValues !== "function")
3101
+ throw new Error("No cryptographic source of randomness is available.");
3102
+ const bytes3 = new Uint8Array(16);
3103
+ webCrypto.getRandomValues(bytes3);
3104
+ bytes3[6] = bytes3[6] & 15 | 64;
3105
+ bytes3[8] = bytes3[8] & 63 | 128;
3106
+ const hex = Array.from(bytes3).map((byte) => byte.toString(16).padStart(2, "0")).join("");
3107
+ return [
3108
+ hex.slice(0, 8),
3109
+ hex.slice(8, 12),
3110
+ hex.slice(12, 16),
3111
+ hex.slice(16, 20),
3112
+ hex.slice(20)
3113
+ ].join("-");
3114
+ };
3115
+ var APP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
3116
+ var isAppId = (value) => typeof value === "string" && APP_ID.test(value);
3117
+
3118
+ // src/appstream/service.ts
3119
+ var appSummary = (entry) => ({
3120
+ id: entry.id,
3121
+ name: entry.name,
3122
+ url: `/app/${entry.id}/`
3123
+ });
3124
+ var webFolderOf = (value) => {
3125
+ if (typeof value !== "string" || value === "")
3126
+ throw new ApiError(400, '"streamWebFolder" is required');
3127
+ if (value === "." || value === ".." || /[\\/]/.test(value))
3128
+ throw new ApiError(400, "streamWebFolder must be a single path segment.");
3129
+ return value;
3130
+ };
3131
+ var defaultAppName = (appLoc) => {
3132
+ const segment = appLoc.split("/").filter(Boolean).pop();
3133
+ return segment ? segment : "app";
3134
+ };
3135
+ var sameAppLoc = (left, right) => {
3136
+ try {
3137
+ return normaliseAppLoc(left) === normaliseAppLoc(right);
3138
+ } catch (_) {
3139
+ return false;
3140
+ }
3141
+ };
3142
+ var appLocOf = (value) => {
3143
+ try {
3144
+ return normaliseAppLoc(value);
3145
+ } catch (error) {
3146
+ throw new ApiError(400, error.message);
3147
+ }
3148
+ };
3149
+ var checkPublishRequest = (request) => {
3150
+ const appLoc = appLocOf(request.appLoc);
3151
+ if (appLoc === "/")
3152
+ throw new ApiError(400, "An app cannot be published at the drive root.");
3153
+ const logo = logoOf(request.logo);
3154
+ const frameAncestors = frameAncestorsOf(request.frameAncestors);
3155
+ return {
3156
+ appLoc,
3157
+ streamWebFolder: webFolderOf(request.streamWebFolder),
3158
+ ...request.name === void 0 ? {} : { name: nameOf(request.name, appLoc) },
3159
+ ...logo === void 0 ? {} : { logo },
3160
+ ...frameAncestors === void 0 ? {} : { frameAncestors },
3161
+ ...request.publishedAt === void 0 ? {} : { publishedAt: request.publishedAt }
3162
+ };
3163
+ };
3164
+ var nameOf = (value, appLoc) => {
3165
+ if (value === void 0) return defaultAppName(appLoc);
3166
+ if (typeof value !== "string" || value.trim() === "")
3167
+ throw new ApiError(400, '"name" must be a non-empty string');
3168
+ return value.trim();
3079
3169
  };
3080
- var MemoryAppStreamRegistry = class {
3081
- constructor(folders = ["/Public/myApp"]) {
3082
- this.folders = new Set(folders);
3170
+ var logoOf = (value) => {
3171
+ if (value === void 0) return void 0;
3172
+ if (typeof value !== "string" || value === "")
3173
+ throw new ApiError(400, '"logo" must be a non-empty string');
3174
+ return value;
3175
+ };
3176
+ var frameAncestorsOf = (value) => {
3177
+ if (value === void 0) return void 0;
3178
+ const list = Array.isArray(value) ? value : [value];
3179
+ if (list.length === 0 || list.some((source) => typeof source !== "string" || source === ""))
3180
+ throw new ApiError(
3181
+ 400,
3182
+ '"frameAncestors" must be a string or a non-empty list of strings'
3183
+ );
3184
+ return [...list];
3185
+ };
3186
+ var createAppStreamService = (store) => {
3187
+ let queue = Promise.resolve();
3188
+ const mutate = (work) => {
3189
+ const run = queue.then(work, work);
3190
+ queue = run.catch(() => void 0);
3191
+ return run;
3192
+ };
3193
+ const readable = (allow) => store.read().then(
3194
+ (entries) => entries.filter((entry) => allow ? allow(entry) : true).map((entry) => ({ ...entry })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
3195
+ );
3196
+ return {
3197
+ list: readable,
3198
+ async get(id) {
3199
+ const entry = (await store.read()).find(
3200
+ (candidate) => candidate.id === id
3201
+ );
3202
+ if (!entry) throw new ApiError(404, "No app is published with that id.");
3203
+ return { ...entry };
3204
+ },
3205
+ async forAppLoc(appLoc) {
3206
+ let normalised;
3207
+ try {
3208
+ normalised = normaliseAppLoc(appLoc);
3209
+ } catch (_) {
3210
+ return void 0;
3211
+ }
3212
+ const entry = (await store.read()).find(
3213
+ (candidate) => sameAppLoc(candidate.appLoc, normalised)
3214
+ );
3215
+ return entry ? { ...entry } : void 0;
3216
+ },
3217
+ publish(request) {
3218
+ return mutate(async () => {
3219
+ const checked = checkPublishRequest(request);
3220
+ const appLoc = checked.appLoc;
3221
+ const streamWebFolder = checked.streamWebFolder;
3222
+ const entries = await store.read();
3223
+ const existing = entries.find(
3224
+ (entry2) => sameAppLoc(entry2.appLoc, appLoc)
3225
+ );
3226
+ const logo = checked.logo;
3227
+ const frameAncestors = checked.frameAncestors;
3228
+ const entry = {
3229
+ id: existing ? existing.id : newAppId(),
3230
+ // the label is the one field a redeploy inherits: everything else is
3231
+ // what this publish states
3232
+ name: nameOf(checked.name ?? existing?.name, appLoc),
3233
+ appLoc,
3234
+ streamWebFolder,
3235
+ ...logo === void 0 ? {} : { logo },
3236
+ ...frameAncestors === void 0 ? {} : { frameAncestors },
3237
+ publishedAt: checked.publishedAt ?? (/* @__PURE__ */ new Date()).toISOString()
3238
+ };
3239
+ await store.write([
3240
+ ...entries.filter(
3241
+ (candidate) => !sameAppLoc(candidate.appLoc, appLoc)
3242
+ ),
3243
+ entry
3244
+ ]);
3245
+ return { ...entry };
3246
+ });
3247
+ },
3248
+ unpublish(id) {
3249
+ return mutate(async () => {
3250
+ const entries = await store.read();
3251
+ const index = entries.findIndex((entry) => entry.id === id);
3252
+ if (index === -1)
3253
+ throw new ApiError(404, "No app is published with that id.");
3254
+ const [removed] = entries.splice(index, 1);
3255
+ await store.write(entries);
3256
+ return { ...removed };
3257
+ });
3258
+ }
3259
+ };
3260
+ };
3261
+ var MemoryAppStreamStore = class {
3262
+ constructor(entries = []) {
3263
+ this.entries = entries.map((entry) => ({ ...entry }));
3083
3264
  }
3084
- async unpublish(appLoc) {
3085
- return this.folders.delete(appLoc);
3265
+ async read() {
3266
+ return this.entries.map((entry) => ({ ...entry }));
3267
+ }
3268
+ async write(entries) {
3269
+ this.entries = entries.map((entry) => ({ ...entry }));
3086
3270
  }
3087
3271
  };
3088
3272
 
3273
+ // src/appstream/bundle.ts
3274
+ var APP_MANIFEST = "sasjs.app.json";
3275
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3276
+ var text = (value, field) => {
3277
+ if (value === void 0) return void 0;
3278
+ if (typeof value !== "string" || value.trim() === "")
3279
+ throw new ApiError(
3280
+ 400,
3281
+ `"${field}" must be a non-empty string in ${APP_MANIFEST}.`
3282
+ );
3283
+ return value.trim();
3284
+ };
3285
+ var parseAppManifest = (value) => {
3286
+ if (!isObject(value))
3287
+ throw new ApiError(400, `${APP_MANIFEST} must be an object.`);
3288
+ const streamWebFolder = text(value.streamWebFolder, "streamWebFolder");
3289
+ if (streamWebFolder === void 0)
3290
+ throw new ApiError(
3291
+ 400,
3292
+ `${APP_MANIFEST} must state "streamWebFolder": the folder under services/ holding the compiled app.`
3293
+ );
3294
+ const name = text(value.name, "name");
3295
+ const logo = text(value.logo, "logo");
3296
+ const frameAncestors = value.frameAncestors;
3297
+ if (frameAncestors !== void 0 && (typeof frameAncestors !== "string" || frameAncestors === "") && !(Array.isArray(frameAncestors) && frameAncestors.length > 0 && frameAncestors.every(
3298
+ (source) => typeof source === "string" && source !== ""
3299
+ )))
3300
+ throw new ApiError(
3301
+ 400,
3302
+ `"frameAncestors" in ${APP_MANIFEST} must be a string or a non-empty list of strings.`
3303
+ );
3304
+ return {
3305
+ ...name === void 0 ? {} : { name },
3306
+ streamWebFolder,
3307
+ ...logo === void 0 ? {} : { logo },
3308
+ ...frameAncestors === void 0 ? {} : { frameAncestors }
3309
+ };
3310
+ };
3311
+ var splitAppBundle = (tree) => {
3312
+ if (!isObject(tree) || !Array.isArray(tree.members))
3313
+ return { tree };
3314
+ const members = tree.members;
3315
+ const at = members.findIndex(
3316
+ (member2) => isObject(member2) && member2.type === "file" && member2.name === APP_MANIFEST
3317
+ );
3318
+ if (at === -1) return { tree };
3319
+ const member = members[at];
3320
+ if (typeof member.code !== "string")
3321
+ throw new ApiError(400, `${APP_MANIFEST} carries no text.`);
3322
+ let parsed;
3323
+ try {
3324
+ parsed = JSON.parse(member.code);
3325
+ } catch (error) {
3326
+ throw new ApiError(
3327
+ 400,
3328
+ `${APP_MANIFEST} is not valid JSON: ${error.message}`
3329
+ );
3330
+ }
3331
+ return {
3332
+ tree: {
3333
+ ...tree,
3334
+ members: members.filter((_, index) => index !== at)
3335
+ },
3336
+ manifest: parseAppManifest(parsed)
3337
+ };
3338
+ };
3339
+ var publishRequestFor = (deploy, manifest) => {
3340
+ const streamWebFolder = deploy.streamWebFolder ?? manifest?.streamWebFolder;
3341
+ if (streamWebFolder === void 0) return void 0;
3342
+ const name = deploy.streamServiceName ?? manifest?.name;
3343
+ const logo = deploy.streamLogo ?? manifest?.logo;
3344
+ return {
3345
+ appLoc: deploy.appLoc,
3346
+ streamWebFolder,
3347
+ ...name === void 0 ? {} : { name },
3348
+ ...logo === void 0 ? {} : { logo },
3349
+ ...manifest?.frameAncestors === void 0 ? {} : { frameAncestors: manifest.frameAncestors }
3350
+ };
3351
+ };
3352
+
3089
3353
  // src/host/dispatch.ts
3090
3354
  var SECONDS_IN_A_DAY = 86400;
3091
3355
  var RUN_ROUTES = [
@@ -3095,15 +3359,16 @@ var SASjsApi = (() => {
3095
3359
  "POST /SASjsApi/code/execute",
3096
3360
  "POST /SASjsApi/code/trigger"
3097
3361
  ];
3362
+ var given = (value) => typeof value === "string" && value !== "" ? value : void 0;
3098
3363
  var validate = (route, request) => {
3099
3364
  for (const param of route.params) {
3100
3365
  if (!param.required || param.in === "formData" || param.in === "header")
3101
3366
  continue;
3102
3367
  if (param.in === "path") continue;
3103
- const given = param.in === "query" ? request.query?.[param.name] : request.body?.[param.name];
3104
- if (given === void 0)
3368
+ const given2 = param.in === "query" ? request.query?.[param.name] : request.body?.[param.name];
3369
+ if (given2 === void 0)
3105
3370
  throw new ApiError(400, `"${param.name}" is required`);
3106
- if (given === "")
3371
+ if (given2 === "")
3107
3372
  throw new ApiError(400, `"${param.name}" is not allowed to be empty`);
3108
3373
  }
3109
3374
  };
@@ -3335,19 +3600,39 @@ var SASjsApi = (() => {
3335
3600
  // expansion, which is why the two share this path rather than reading bytes.
3336
3601
  case "POST /SASjsApi/drive/deploy/upload":
3337
3602
  case "POST /SASjsApi/drive/deploy": {
3338
- await drive.deploy(String(body.appLoc ?? ""), body.fileTree);
3339
- return { status: 200, body: DEPLOY_SUCCESS };
3603
+ const bundle = splitAppBundle(body.fileTree);
3604
+ const appLoc = String(body.appLoc ?? "");
3605
+ const requested = services.appStream ? publishRequestFor(
3606
+ {
3607
+ appLoc,
3608
+ streamWebFolder: given(body.streamWebFolder),
3609
+ streamServiceName: given(body.streamServiceName),
3610
+ streamLogo: given(body.streamLogo)
3611
+ },
3612
+ bundle.manifest
3613
+ ) : void 0;
3614
+ const publish = requested === void 0 ? void 0 : checkPublishRequest(requested);
3615
+ await drive.deploy(appLoc, bundle.tree);
3616
+ if (publish === void 0 || !services.appStream)
3617
+ return { status: 200, body: DEPLOY_SUCCESS };
3618
+ const entry = await services.appStream.publish(publish);
3619
+ return {
3620
+ status: 200,
3621
+ body: { ...DEPLOY_SUCCESS, app: appSummary(entry) }
3622
+ };
3340
3623
  }
3341
- case "DELETE /SASjsApi/drive/deploy":
3342
- if (!services.registry)
3624
+ case "DELETE /SASjsApi/drive/deploy": {
3625
+ if (!services.appStream)
3343
3626
  throw new ApiError(
3344
3627
  501,
3345
- `This host has no app stream registry, so it cannot answer ${routeId}.`
3628
+ `This host has no app stream, so it cannot answer ${routeId}.`
3346
3629
  );
3630
+ const removed = await services.appStream.unpublish(String(body.id ?? ""));
3347
3631
  return {
3348
3632
  status: 200,
3349
- body: await unpublishAppStream(services.registry, body)
3633
+ body: { status: "success", app: appSummary(removed) }
3350
3634
  };
3635
+ }
3351
3636
  case "GET /SASjsApi/drive/filetree":
3352
3637
  return { status: 200, body: await drive.tree(query._folderPath) };
3353
3638
  // ------------------------------------------------------------- run times
@@ -4470,7 +4755,7 @@ var SASjsApi = (() => {
4470
4755
  var BUNDLE_REFERENCE = new RegExp(
4471
4756
  `(^|/)${BUNDLE_NAME.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`
4472
4757
  );
4473
- var withBundleVersion = (html, version) => html.replace(FILE_ATTRIBUTE, (match, attribute, value) => {
4758
+ var withBundleVersion = (html2, version) => html2.replace(FILE_ATTRIBUTE, (match, attribute, value) => {
4474
4759
  const quote = value[0] === '"' || value[0] === "'" ? value[0] : "";
4475
4760
  const target = quote ? value.slice(1, -1) : value;
4476
4761
  if (!BUNDLE_REFERENCE.test(target) || target.includes("?")) return match;
@@ -4703,7 +4988,7 @@ var SASjsApi = (() => {
4703
4988
  // src/admin/service.ts
4704
4989
  var DEFAULT_LOG_LINES = 200;
4705
4990
  var MAX_LOG_LINES = 5e3;
4706
- var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
4991
+ var isObject2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
4707
4992
  var isNumber = (value) => typeof value === "number" && Number.isFinite(value);
4708
4993
  var isString = (value) => typeof value === "string";
4709
4994
  var requireString = (holder, key, where) => {
@@ -4720,14 +5005,14 @@ var SASjsApi = (() => {
4720
5005
  };
4721
5006
  var requireObject = (holder, key, where) => {
4722
5007
  const value = holder[key];
4723
- if (!isObject(value))
5008
+ if (!isObject2(value))
4724
5009
  throw new Error(
4725
5010
  `The ${where} report states \`${key}\` as ${JSON.stringify(value)}; the document states an object.`
4726
5011
  );
4727
5012
  return value;
4728
5013
  };
4729
5014
  var normaliseDiagnostics = (report) => {
4730
- if (!isObject(report))
5015
+ if (!isObject2(report))
4731
5016
  throw new Error("The diagnostics report is not an object.");
4732
5017
  const build = requireObject(
4733
5018
  report,
@@ -4779,7 +5064,7 @@ var SASjsApi = (() => {
4779
5064
  requireNumber(memory, key, "diagnostics memory");
4780
5065
  const filesystem = report.filesystem;
4781
5066
  if (filesystem !== null) {
4782
- if (!isObject(filesystem))
5067
+ if (!isObject2(filesystem))
4783
5068
  throw new Error(
4784
5069
  `The diagnostics report states \`filesystem\` as ${JSON.stringify(filesystem)}; the document states an object or null.`
4785
5070
  );
@@ -4800,7 +5085,7 @@ var SASjsApi = (() => {
4800
5085
  "The diagnostics report states `folders` as something other than an array."
4801
5086
  );
4802
5087
  for (const folder of report.folders) {
4803
- if (!isObject(folder))
5088
+ if (!isObject2(folder))
4804
5089
  throw new Error(
4805
5090
  "The diagnostics report carries a folder that is not an object."
4806
5091
  );
@@ -4833,7 +5118,7 @@ var SASjsApi = (() => {
4833
5118
  if (!Array.isArray(files))
4834
5119
  throw new Error("The log report is not an array of files.");
4835
5120
  return files.map((file) => {
4836
- if (!isObject(file))
5121
+ if (!isObject2(file))
4837
5122
  throw new Error("The log report carries an entry that is not an object.");
4838
5123
  const entry = file;
4839
5124
  requireString(entry, "name", "logs");
@@ -4855,7 +5140,7 @@ var SASjsApi = (() => {
4855
5140
  return Math.min(Math.max(Math.trunc(wanted), 1), MAX_LOG_LINES);
4856
5141
  };
4857
5142
  var normaliseLogTail = (tail) => {
4858
- if (!isObject(tail)) throw new Error("The log tail report is not an object.");
5143
+ if (!isObject2(tail)) throw new Error("The log tail report is not an object.");
4859
5144
  const entry = tail;
4860
5145
  requireString(entry, "fileName", "log tail");
4861
5146
  requireString(entry, "content", "log tail");
@@ -6117,46 +6402,35 @@ var SASjsApi = (() => {
6117
6402
  {
6118
6403
  id: "deploy-unpublish",
6119
6404
  route: "DELETE /SASjsApi/drive/deploy",
6120
- description: "removes a published app stream and answers the status",
6121
- request: {
6122
- subject: SUBJECT,
6123
- body: { streamServiceName: "myApp", appLoc: "/Public/myApp" }
6124
- },
6125
- expect: { status: 200, body: { status: "success" } }
6126
- },
6127
- {
6128
- id: "deploy-unpublish-other-name",
6129
- route: "DELETE /SASjsApi/drive/deploy",
6130
- description: "removes the app by its folder when the name has been renamed",
6405
+ description: "removes the app the id names, and says what went",
6131
6406
  request: {
6132
6407
  subject: SUBJECT,
6133
- body: { streamServiceName: "renamed-app", appLoc: "/Public/myApp" }
6408
+ body: { id: "6f1c1c1e-6a1e-4c4a-9d1a-1b2c3d4e5f60" }
6134
6409
  },
6135
- expect: { status: 200, body: { status: "success" } }
6136
- },
6137
- {
6138
- id: "deploy-unpublish-no-stream-name",
6139
- route: "DELETE /SASjsApi/drive/deploy",
6140
- description: "refuses a body that does not say which stream to remove",
6141
- request: { subject: SUBJECT, body: { appLoc: "/Public/myApp" } },
6142
- expect: { status: 400, error: '"streamServiceName" is required' }
6410
+ expect: {
6411
+ status: 200,
6412
+ partial: {
6413
+ status: "success",
6414
+ app: { id: "6f1c1c1e-6a1e-4c4a-9d1a-1b2c3d4e5f60", name: "myApp" }
6415
+ }
6416
+ }
6143
6417
  },
6144
6418
  {
6145
- id: "deploy-unpublish-no-app-loc",
6419
+ id: "deploy-unpublish-no-id",
6146
6420
  route: "DELETE /SASjsApi/drive/deploy",
6147
- description: "refuses a body that does not say which folder to remove",
6148
- request: { subject: SUBJECT, body: { streamServiceName: "myApp" } },
6149
- expect: { status: 400, error: '"appLoc" is required' }
6421
+ description: "refuses a body that does not say which app to remove",
6422
+ request: { subject: SUBJECT, body: {} },
6423
+ expect: { status: 400, error: '"id" is required' }
6150
6424
  },
6151
6425
  {
6152
- id: "deploy-unpublish-unknown-folder",
6426
+ id: "deploy-unpublish-unknown-id",
6153
6427
  route: "DELETE /SASjsApi/drive/deploy",
6154
- description: "answers 404 for a folder nothing is published at",
6428
+ description: "answers 404 for an id the index does not hold",
6155
6429
  request: {
6156
6430
  subject: SUBJECT,
6157
- body: { streamServiceName: "myApp", appLoc: "/Public/not-an-app" }
6431
+ body: { id: "11111111-1111-4111-8111-111111111111" }
6158
6432
  },
6159
- expect: { status: 404, error: "No app is published at that folder." }
6433
+ expect: { status: 404, error: "No app is published with that id." }
6160
6434
  },
6161
6435
  // ------------------------------------------- the uploaded-archive route
6162
6436
  // The archive is expanded by the host, so what arrives here is the same tree
@@ -6171,7 +6445,35 @@ var SASjsApi = (() => {
6171
6445
  appLoc: "/Public/apps/uploaded",
6172
6446
  fileTree: {
6173
6447
  members: [
6174
- { name: "index.html", type: "file", code: "PGgxPkhlbGxvPC9oMT4=" }
6448
+ {
6449
+ name: "index.html",
6450
+ type: "file",
6451
+ code: "PGgxPkhlbGxvPC9oMT4=",
6452
+ encoding: "base64"
6453
+ }
6454
+ ]
6455
+ }
6456
+ }
6457
+ },
6458
+ expect: {
6459
+ status: 200,
6460
+ body: {
6461
+ status: "success",
6462
+ message: "Files deployed successfully to @sasjs/server."
6463
+ }
6464
+ }
6465
+ },
6466
+ {
6467
+ id: "upload-text-file",
6468
+ route: "POST /SASjsApi/drive/deploy/upload",
6469
+ description: "writes a file member as its own text when no encoding is stated",
6470
+ request: {
6471
+ subject: SUBJECT,
6472
+ body: {
6473
+ appLoc: "/Public/apps/text",
6474
+ fileTree: {
6475
+ members: [
6476
+ { name: "index.html", type: "file", code: "<h1>Hello</h1>" }
6175
6477
  ]
6176
6478
  }
6177
6479
  }
@@ -6221,6 +6523,72 @@ var SASjsApi = (() => {
6221
6523
  error: "The file tree exceeds the deploy limit: 10001 entries (maximum 10000)."
6222
6524
  }
6223
6525
  },
6526
+ // ------------------------------------------- a bundle that is an app
6527
+ // One deploy writes the tree and indexes the app, from the manifest at the
6528
+ // root of the archive. The id is minted, so the case pins what can be pinned:
6529
+ // the app exists, under the label the manifest states.
6530
+ {
6531
+ id: "deploy-publishes-an-app",
6532
+ route: "POST /SASjsApi/drive/deploy",
6533
+ description: "indexes a bundle as an app from the manifest it carries, in one request",
6534
+ request: {
6535
+ subject: SUBJECT,
6536
+ body: {
6537
+ appLoc: "/Public/apps/mario",
6538
+ fileTree: {
6539
+ members: [
6540
+ {
6541
+ name: "sasjs.app.json",
6542
+ type: "file",
6543
+ code: JSON.stringify({
6544
+ name: "Mario",
6545
+ streamWebFolder: "web",
6546
+ logo: "logo.png"
6547
+ })
6548
+ },
6549
+ {
6550
+ name: "services",
6551
+ type: "folder",
6552
+ members: [
6553
+ {
6554
+ name: "web",
6555
+ type: "folder",
6556
+ members: [
6557
+ { name: "index.html", type: "file", code: "<h1>Mario</h1>" }
6558
+ ]
6559
+ },
6560
+ { name: "run", type: "service", code: "%put hi;" }
6561
+ ]
6562
+ }
6563
+ ]
6564
+ }
6565
+ }
6566
+ },
6567
+ expect: {
6568
+ status: 200,
6569
+ partial: {
6570
+ status: "success",
6571
+ app: { name: "Mario" }
6572
+ }
6573
+ }
6574
+ },
6575
+ {
6576
+ id: "deploy-refuses-a-bad-manifest",
6577
+ route: "POST /SASjsApi/drive/deploy",
6578
+ description: "refuses a bundle whose manifest is not JSON",
6579
+ request: {
6580
+ subject: SUBJECT,
6581
+ body: {
6582
+ appLoc: "/Public/apps/bad-manifest",
6583
+ fileTree: {
6584
+ members: [{ name: "sasjs.app.json", type: "file", code: "{not json" }]
6585
+ }
6586
+ }
6587
+ },
6588
+ expect: {
6589
+ status: 400
6590
+ }
6591
+ },
6224
6592
  {
6225
6593
  id: "upload-refused-by-store",
6226
6594
  route: "POST /SASjsApi/drive/deploy/upload",
@@ -6521,9 +6889,9 @@ var SASjsApi = (() => {
6521
6889
  if (value === void 0 || value === null || value === "") return void 0;
6522
6890
  if (typeof value === "number")
6523
6891
  return Number.isFinite(value) ? value : void 0;
6524
- const text = String(value).trim();
6525
- if (!text) return void 0;
6526
- return /^[+-]?\d+$/.test(text) ? Number(text) : CODE_DEBUG;
6892
+ const text2 = String(value).trim();
6893
+ if (!text2) return void 0;
6894
+ return /^[+-]?\d+$/.test(text2) ? Number(text2) : CODE_DEBUG;
6527
6895
  };
6528
6896
  var pad = (value) => String(value).padStart(2, "0");
6529
6897
  var timestamp = (now) => [
@@ -8177,6 +8545,13 @@ var SASjsApi = (() => {
8177
8545
  ];
8178
8546
 
8179
8547
  // src/corpus/runner.ts
8548
+ var CORPUS_APP = {
8549
+ id: "6f1c1c1e-6a1e-4c4a-9d1a-1b2c3d4e5f60",
8550
+ name: "myApp",
8551
+ appLoc: "/Public/myApp",
8552
+ streamWebFolder: "web",
8553
+ publishedAt: "2026-01-01T00:00:00.000Z"
8554
+ };
8180
8555
  var servicesFor = (testCase) => {
8181
8556
  const identity = new MemoryIdentityStore(
8182
8557
  testCase.identity || DEFAULT_IDENTITY
@@ -8200,7 +8575,7 @@ var SASjsApi = (() => {
8200
8575
  directory: createDirectoryService(identity, CORPUS_DIRECTORY),
8201
8576
  identity: createIdentityService(identity),
8202
8577
  records: createRecordService(identity),
8203
- registry: new MemoryAppStreamRegistry(),
8578
+ appStream: createAppStreamService(new MemoryAppStreamStore([CORPUS_APP])),
8204
8579
  session: createSessionService(identity, runner),
8205
8580
  // no `runTimes` option: the default is the five the document names, so a
8206
8581
  // case is never refused for a reason that belongs to one host's install
@@ -8232,6 +8607,225 @@ var SASjsApi = (() => {
8232
8607
  throw error;
8233
8608
  }
8234
8609
  };
8610
+
8611
+ // src/appstream/store.ts
8612
+ var APP_STREAM_INDEX = "/.sasjs/apps.json";
8613
+ var isEntry = (value) => {
8614
+ if (typeof value !== "object" || value === null) return false;
8615
+ const entry = value;
8616
+ return typeof entry.id === "string" && typeof entry.name === "string" && typeof entry.appLoc === "string" && typeof entry.streamWebFolder === "string" && typeof entry.publishedAt === "string";
8617
+ };
8618
+ var createDriveAppStreamStore = (drive, filePath2 = APP_STREAM_INDEX) => ({
8619
+ async read() {
8620
+ let contents;
8621
+ try {
8622
+ contents = (await drive.read(filePath2)).contents;
8623
+ } catch (error) {
8624
+ if (error instanceof ApiError && error.status === 404) return [];
8625
+ throw error;
8626
+ }
8627
+ if (typeof contents !== "string")
8628
+ throw new ApiError(
8629
+ 500,
8630
+ `The app index at ${filePath2} is not text, so no app can be read from it.`
8631
+ );
8632
+ let parsed;
8633
+ try {
8634
+ parsed = JSON.parse(contents);
8635
+ } catch (error) {
8636
+ throw new ApiError(
8637
+ 500,
8638
+ `The app index at ${filePath2} is not valid JSON, so no app is registered: ${error.message}`
8639
+ );
8640
+ }
8641
+ if (!Array.isArray(parsed) || !parsed.every(isEntry))
8642
+ throw new ApiError(
8643
+ 500,
8644
+ `The app index at ${filePath2} is not a list of app entries, so no app is registered.`
8645
+ );
8646
+ return parsed;
8647
+ },
8648
+ async write(entries) {
8649
+ const contents = JSON.stringify(entries, null, 2);
8650
+ try {
8651
+ await drive.update(filePath2, contents);
8652
+ } catch (error) {
8653
+ if (error instanceof ApiError && error.status === 404) {
8654
+ await drive.save(filePath2, contents);
8655
+ return;
8656
+ }
8657
+ throw error;
8658
+ }
8659
+ }
8660
+ });
8661
+
8662
+ // src/appstream/web.ts
8663
+ var DEFAULT_APP_PATH = "/app";
8664
+ var NO_SUCH_APP = "There's no App Stream available here.";
8665
+ var ESCAPES = {
8666
+ "&": "&amp;",
8667
+ "<": "&lt;",
8668
+ ">": "&gt;",
8669
+ '"': "&quot;",
8670
+ "'": "&#39;"
8671
+ };
8672
+ var escapeHtml = (value) => value.replace(/[&<>"']/g, (character) => ESCAPES[character]);
8673
+ var CONTENT_TYPES = {
8674
+ html: "text/html; charset=utf-8",
8675
+ htm: "text/html; charset=utf-8",
8676
+ js: "text/javascript; charset=utf-8",
8677
+ mjs: "text/javascript; charset=utf-8",
8678
+ css: "text/css; charset=utf-8",
8679
+ json: "application/json; charset=utf-8",
8680
+ map: "application/json; charset=utf-8",
8681
+ txt: "text/plain; charset=utf-8",
8682
+ svg: "image/svg+xml",
8683
+ png: "image/png",
8684
+ jpg: "image/jpeg",
8685
+ jpeg: "image/jpeg",
8686
+ gif: "image/gif",
8687
+ webp: "image/webp",
8688
+ ico: "image/x-icon",
8689
+ woff: "font/woff",
8690
+ woff2: "font/woff2",
8691
+ ttf: "font/ttf",
8692
+ otf: "font/otf",
8693
+ wasm: "application/wasm",
8694
+ pdf: "application/pdf",
8695
+ zip: "application/zip"
8696
+ };
8697
+ var contentTypeFor = (filePath2) => {
8698
+ const extension = filePath2.slice(filePath2.lastIndexOf(".") + 1).toLowerCase();
8699
+ return CONTENT_TYPES[extension] ?? "application/octet-stream";
8700
+ };
8701
+ var cacheControlFor = (filePath2) => /\.[0-9a-f]{8,}\.[A-Za-z0-9]+$/.test(filePath2) ? "public, max-age=31536000, immutable" : "public, max-age=0, must-revalidate";
8702
+ var html = (status, markup) => ({
8703
+ status,
8704
+ body: markup,
8705
+ contentType: "text/html; charset=utf-8"
8706
+ });
8707
+ var json = (status, body) => ({
8708
+ status,
8709
+ body: JSON.stringify(body),
8710
+ contentType: "application/json; charset=utf-8"
8711
+ });
8712
+ var noSuchApp = () => html(404, `<!doctype html><html><body>${NO_SUCH_APP}</body></html>`);
8713
+ var methodNotAllowed = (allowed) => ({
8714
+ status: 405,
8715
+ body: JSON.stringify({ status: "failure", message: `${allowed} only.` }),
8716
+ contentType: "application/json; charset=utf-8",
8717
+ headers: { allow: allowed }
8718
+ });
8719
+ var decoded = (segment) => {
8720
+ try {
8721
+ return decodeURIComponent(segment);
8722
+ } catch (_) {
8723
+ return void 0;
8724
+ }
8725
+ };
8726
+ var createAppStreamWebService = (appStream, drive, options = {}) => {
8727
+ const base = (options.basePath ?? DEFAULT_APP_PATH).replace(/\/+$/, "");
8728
+ const title = options.title ?? "SASjs App Stream";
8729
+ const urlOf = (entry) => `${base}/${entry.id}/`;
8730
+ const rowOf = (entry) => ({
8731
+ id: entry.id,
8732
+ name: entry.name,
8733
+ appLoc: entry.appLoc,
8734
+ logo: entry.logo === void 0 ? null : `${urlOf(entry)}${entry.logo}`,
8735
+ url: urlOf(entry),
8736
+ publishedAt: entry.publishedAt ?? null
8737
+ });
8738
+ const apps = async (allow) => {
8739
+ const entries = await appStream.list(allow);
8740
+ return { apps: entries.map(rowOf) };
8741
+ };
8742
+ const landing = async (allow) => {
8743
+ const { apps: rows } = await apps(allow);
8744
+ const tiles = rows.length ? `<ul class="apps">${rows.map(
8745
+ (row) => `<li><a href="${escapeHtml(row.url)}">${escapeHtml(row.name)}</a><span class="loc">${escapeHtml(row.appLoc)}</span></li>`
8746
+ ).join("")}</ul>` : '<p class="empty">No apps have been published yet.</p>';
8747
+ return html(
8748
+ 200,
8749
+ [
8750
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">',
8751
+ '<meta name="viewport" content="width=device-width,initial-scale=1">',
8752
+ `<title>${escapeHtml(title)}</title>`,
8753
+ "<style>",
8754
+ "body{font-family:system-ui,sans-serif;margin:2rem;color:#1f2430}",
8755
+ "h1{font-size:1.4rem}",
8756
+ "ul.apps{list-style:none;padding:0;display:grid;gap:.75rem;max-width:40rem}",
8757
+ "ul.apps li{display:flex;flex-direction:column;gap:.15rem;padding:.75rem 1rem;",
8758
+ "border:1px solid #d8dee9;border-radius:.5rem}",
8759
+ "ul.apps a{font-weight:600;text-decoration:none;color:#0b5cad}",
8760
+ ".loc{font-size:.8rem;color:#5b6472;font-family:ui-monospace,monospace}",
8761
+ ".empty{color:#5b6472}",
8762
+ "</style></head><body>",
8763
+ `<h1>${escapeHtml(title)}</h1>`,
8764
+ tiles,
8765
+ "</body></html>"
8766
+ ].join("")
8767
+ );
8768
+ };
8769
+ const resolve = async (segment, allow) => {
8770
+ const entries = await appStream.list(allow);
8771
+ const byId2 = entries.find((entry) => entry.id === segment);
8772
+ if (byId2) return byId2;
8773
+ const byName = entries.filter((entry) => entry.name === segment);
8774
+ return byName.length === 1 ? byName[0] : void 0;
8775
+ };
8776
+ const asset = async (entry, segments) => {
8777
+ const parts = segments.map(decoded);
8778
+ if (parts.some((part) => part === void 0)) return noSuchApp();
8779
+ const relative = parts.join("/") || "index.html";
8780
+ try {
8781
+ const file = await drive.read(
8782
+ `${entry.appLoc}/services/${entry.streamWebFolder}/${relative}`
8783
+ );
8784
+ return {
8785
+ status: 200,
8786
+ body: file.contents,
8787
+ contentType: contentTypeFor(relative),
8788
+ headers: { "cache-control": cacheControlFor(relative) }
8789
+ };
8790
+ } catch (error) {
8791
+ if (error instanceof ApiError && (error.status === 404 || error.status === 400))
8792
+ return noSuchApp();
8793
+ throw error;
8794
+ }
8795
+ };
8796
+ return {
8797
+ apps,
8798
+ landing,
8799
+ async request({ method, path, allow }) {
8800
+ const clean = (path.split(/[?#]/)[0] || "/").replace(/\/{2,}/g, "/");
8801
+ const relative = base === "" ? clean : clean === base ? "/" : clean.startsWith(`${base}/`) ? clean.slice(base.length) : null;
8802
+ if (relative === null) return noSuchApp();
8803
+ if (relative === "" || relative === "/" || relative === "/index.html") {
8804
+ if (method !== "GET") return methodNotAllowed("GET");
8805
+ return landing(allow);
8806
+ }
8807
+ if (relative === "/apps.json") {
8808
+ if (method !== "GET") return methodNotAllowed("GET");
8809
+ return json(200, await apps(allow));
8810
+ }
8811
+ const segments = relative.split("/").filter(Boolean);
8812
+ const key = decoded(segments[0]);
8813
+ if (key === void 0) return noSuchApp();
8814
+ if (method === "DELETE") {
8815
+ const entry2 = await resolve(key, allow);
8816
+ if (!entry2) return noSuchApp();
8817
+ const removed = await appStream.unpublish(entry2.id);
8818
+ return json(200, { status: "success", app: rowOf(removed) });
8819
+ }
8820
+ if (method !== "GET") return methodNotAllowed("GET, DELETE");
8821
+ const entry = await resolve(key, allow);
8822
+ if (!entry) return noSuchApp();
8823
+ if (segments.length === 1 && !relative.endsWith("/"))
8824
+ return { status: 301, location: urlOf(entry) };
8825
+ return asset(entry, segments.slice(1));
8826
+ }
8827
+ };
8828
+ };
8235
8829
  return __toCommonJS(index_exports);
8236
8830
  })();
8237
8831
  if (typeof self !== 'undefined') self.SASjsApi = SASjsApi