@panomc/sdk 1.0.0-dev.8 → 2.0.0-dev.1

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 (166) hide show
  1. package/api/routes.core.json +3702 -0
  2. package/bin/api/__tests__/api-compat.test.mjs +97 -0
  3. package/bin/api/__tests__/check-paths.test.mjs +113 -0
  4. package/bin/api/__tests__/cli.test.mjs +44 -0
  5. package/bin/api/__tests__/extract-routes.test.mjs +132 -0
  6. package/bin/api/__tests__/fixtures/core-new/Pano/api/paths.old-new.json +82 -0
  7. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  8. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  9. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  10. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  11. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  12. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  13. package/bin/api/__tests__/fixtures/core-new/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  14. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/error/NotExists.kt +10 -0
  15. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/model/Bases.kt +21 -0
  16. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/GetSiteInfoAPI.kt +19 -0
  17. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/auth/HostSsoAPI.kt +10 -0
  18. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/panel/PanelAddonsAPI.kt +28 -0
  19. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/api/plugins/GetPluginUiZipAPI.kt +9 -0
  20. package/bin/api/__tests__/fixtures/core-old/Pano/src/main/kotlin/com/panomc/platform/route/template/IndexTemplate.kt +9 -0
  21. package/bin/api/__tests__/fixtures/plugin-new/api/paths.old-new.json +66 -0
  22. package/bin/api/__tests__/fixtures/plugin-new/build.gradle.kts +42 -0
  23. package/bin/api/__tests__/fixtures/plugin-new/gradle.properties +4 -0
  24. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  25. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  26. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  27. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  28. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  29. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  30. package/bin/api/__tests__/fixtures/plugin-new/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  31. package/bin/api/__tests__/fixtures/plugin-new/src/panel/Things.js +4 -0
  32. package/bin/api/__tests__/fixtures/plugin-new/src/theme/Logo.svelte +9 -0
  33. package/bin/api/__tests__/fixtures/plugin-new/src/theme/api.js +29 -0
  34. package/bin/api/__tests__/fixtures/plugin-old/build.gradle.kts +22 -0
  35. package/bin/api/__tests__/fixtures/plugin-old/gradle.properties +4 -0
  36. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/base/DemoApis.kt +13 -0
  37. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Errors.kt +16 -0
  38. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/error/Plain.kt +4 -0
  39. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/GetThingsAPI.kt +16 -0
  40. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/PanelThingAPI.kt +11 -0
  41. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/ValidatedAPI.kt +18 -0
  42. package/bin/api/__tests__/fixtures/plugin-old/src/main/kotlin/com/example/demo/routes/WebhookAPI.kt +23 -0
  43. package/bin/api/__tests__/fixtures/plugin-old/src/panel/Things.js +4 -0
  44. package/bin/api/__tests__/fixtures/plugin-old/src/theme/Logo.svelte +9 -0
  45. package/bin/api/__tests__/fixtures/plugin-old/src/theme/api.js +29 -0
  46. package/bin/api/__tests__/fixtures/refusals/gradle.properties +1 -0
  47. package/bin/api/__tests__/fixtures/refusals/src/main/kotlin/x/Bad.kt +39 -0
  48. package/bin/api/__tests__/fixtures/unresolved/src/main/kotlin/x/Orphan.kt +19 -0
  49. package/bin/api/__tests__/helpers.mjs +48 -0
  50. package/bin/api/__tests__/migrate-v1.test.mjs +377 -0
  51. package/bin/api/__tests__/openapi-snapshot.test.mjs +120 -0
  52. package/bin/api/api-compat.mjs +204 -0
  53. package/bin/api/check-paths.mjs +135 -0
  54. package/bin/api/cli.mjs +83 -0
  55. package/bin/api/extract-routes.mjs +129 -0
  56. package/bin/api/js-scan.mjs +337 -0
  57. package/bin/api/kotlin.mjs +366 -0
  58. package/bin/api/migrate-v1.mjs +330 -0
  59. package/bin/api/openapi-snapshot.mjs +112 -0
  60. package/bin/api/project.mjs +172 -0
  61. package/bin/api/rename-table.mjs +66 -0
  62. package/bin/api/util.mjs +194 -0
  63. package/bin/pano-api.js +5 -0
  64. package/build/plugin-api-rollup.js +46 -0
  65. package/core/css/pano-tokens.css +225 -0
  66. package/core/favicon/apple-touch-icon.png +0 -0
  67. package/core/favicon/favicon-96x96.png +0 -0
  68. package/core/favicon/favicon.ico +0 -0
  69. package/core/favicon/favicon.svg +1 -0
  70. package/core/favicon/site.webmanifest +21 -0
  71. package/core/favicon/web-app-manifest-192x192.png +0 -0
  72. package/core/favicon/web-app-manifest-512x512.png +0 -0
  73. package/core/favicon_old/android-icon-144x144.png +0 -0
  74. package/core/favicon_old/android-icon-192x192.png +0 -0
  75. package/core/favicon_old/android-icon-36x36.png +0 -0
  76. package/core/favicon_old/android-icon-48x48.png +0 -0
  77. package/core/favicon_old/android-icon-72x72.png +0 -0
  78. package/core/favicon_old/android-icon-96x96.png +0 -0
  79. package/core/favicon_old/apple-icon-114x114.png +0 -0
  80. package/core/favicon_old/apple-icon-120x120.png +0 -0
  81. package/core/favicon_old/apple-icon-144x144.png +0 -0
  82. package/core/favicon_old/apple-icon-152x152.png +0 -0
  83. package/core/favicon_old/apple-icon-180x180.png +0 -0
  84. package/core/favicon_old/apple-icon-57x57.png +0 -0
  85. package/core/favicon_old/apple-icon-60x60.png +0 -0
  86. package/core/favicon_old/apple-icon-72x72.png +0 -0
  87. package/core/favicon_old/apple-icon-76x76.png +0 -0
  88. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  89. package/core/favicon_old/apple-icon.png +0 -0
  90. package/core/favicon_old/browserconfig.xml +11 -0
  91. package/core/favicon_old/favicon-16x16.png +0 -0
  92. package/core/favicon_old/favicon-32x32.png +0 -0
  93. package/core/favicon_old/favicon-96x96.png +0 -0
  94. package/core/favicon_old/favicon.ico +0 -0
  95. package/core/favicon_old/manifest.json +41 -0
  96. package/core/favicon_old/ms-icon-144x144.png +0 -0
  97. package/core/favicon_old/ms-icon-150x150.png +0 -0
  98. package/core/favicon_old/ms-icon-310x310.png +0 -0
  99. package/core/favicon_old/ms-icon-70x70.png +0 -0
  100. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  101. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  102. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  103. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  104. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  105. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  106. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  107. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  108. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  109. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  110. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  111. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  112. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  113. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  114. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  115. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  116. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  117. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  118. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  119. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  120. package/core/js/ControllerRegistry.js +421 -0
  121. package/core/js/NotificationManager.js +62 -0
  122. package/core/js/PluginAPI.js +39 -0
  123. package/core/js/PluginManager.js +851 -0
  124. package/core/js/RouteMatcher.js +142 -0
  125. package/core/js/__tests__/ControllerRegistry.test.js +378 -0
  126. package/core/js/__tests__/NotificationManager.test.js +57 -0
  127. package/core/js/__tests__/PluginAPI.test.js +25 -0
  128. package/core/js/__tests__/RouteMatcher.test.js +33 -0
  129. package/core/js/__tests__/accessClient.test.js +582 -0
  130. package/core/js/__tests__/api.util.v1.test.js +336 -0
  131. package/core/js/__tests__/appStores.test.js +47 -0
  132. package/core/js/__tests__/devBounce.test.js +28 -0
  133. package/core/js/__tests__/html.util.test.js +18 -0
  134. package/core/js/__tests__/pluginFolder.util.test.js +106 -0
  135. package/core/js/__tests__/pluginPackage.test.js +134 -0
  136. package/core/js/__tests__/pluginUiZip.test.js +47 -0
  137. package/core/js/__tests__/sdkLevel.test.js +34 -0
  138. package/core/js/api.util.js +433 -0
  139. package/core/js/appStores.js +93 -0
  140. package/core/js/basePath.js +10 -0
  141. package/core/js/html.util.js +26 -0
  142. package/core/js/pluginFolder.util.js +95 -0
  143. package/core/js/tooltip.util.js +59 -0
  144. package/core/js/variables.js +95 -0
  145. package/core/js/version.util.js +100 -0
  146. package/core/scss/_pano-tokens.scss +51 -0
  147. package/core/scss/custom-bootstrap.scss +210 -0
  148. package/core/scss/fonts.scss +85 -0
  149. package/core/scss/main.scss +389 -0
  150. package/core/scss/themes.scss +122 -0
  151. package/package.json +63 -11
  152. package/src/__tests__/controllers.test.js +220 -0
  153. package/src/__tests__/views.spike.test.js +472 -0
  154. package/src/components/{index.js → panel.js} +9 -6
  155. package/src/components/theme.js +18 -0
  156. package/src/controllers.js +127 -0
  157. package/src/index.js +1 -1
  158. package/src/runtime-specifiers.js +88 -0
  159. package/src/svelte.js +3 -2
  160. package/src/types.js +5 -3
  161. package/src/utils/api.js +42 -1
  162. package/src/utils/auth.js +8 -0
  163. package/src/utils/component.js +4 -2
  164. package/src/utils/route.js +16 -0
  165. package/src/utils/text.js +8 -0
  166. package/src/views.js +29 -0
@@ -0,0 +1,47 @@
1
+ import { describe, expect, mock, test } from 'bun:test';
2
+ import { writable } from 'svelte/store';
3
+
4
+ // FX-01: a theme process downloads a plugin's UI zip from `/plugins/<id>/_/ui.zip` (relative to /api/v1).
5
+
6
+ const calls = [];
7
+ const ApiUtil = {
8
+ get: async (options) => {
9
+ calls.push(options);
10
+ return new Blob(['zip']);
11
+ },
12
+ };
13
+
14
+ mock.module('$lib/api.util.js', () => ({ default: ApiUtil }));
15
+ mock.module('$lib/PluginAPI.js', () => ({
16
+ init: () => {},
17
+ panoApiClient: {},
18
+ panoApiServer: {},
19
+ }));
20
+ mock.module('$app/env', () => ({ browser: false, dev: false }));
21
+ mock.module('$app/paths', () => ({ base: '' }));
22
+ mock.module('@sveltejs/kit', () => ({
23
+ error: (status, message) => Object.assign(new Error(`HTTP ${status} ${message ?? ''}`), { status }),
24
+ }));
25
+ mock.module('svelte/store', () => ({ writable, get: (store) => { let v; store.subscribe((x) => (v = x))(); return v; } }));
26
+
27
+ const manager = await import('../PluginManager.js');
28
+
29
+ describe('downloadPluginUiZip', () => {
30
+ test('asks the core endpoint relative to /api/v1, as a blob', async () => {
31
+ calls.length = 0;
32
+ const file = await manager.downloadPluginUiZip('pano-plugin-market');
33
+
34
+ expect(calls).toHaveLength(1);
35
+ expect(calls[0].path).toBe('/plugins/pano-plugin-market/_/ui.zip');
36
+ expect(calls[0].blob).toBe(true);
37
+ expect(file).toBeInstanceOf(Blob);
38
+ });
39
+
40
+ test('no path literal of the file starts with /api', async () => {
41
+ const { readFileSync } = await import('node:fs');
42
+ const source = readFileSync(new URL('../PluginManager.js', import.meta.url), 'utf8');
43
+
44
+ expect(source).not.toMatch(/\/api\//);
45
+ expect(source).not.toContain('resources/plugin-ui.zip');
46
+ });
47
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, mock, spyOn, test } from 'bun:test';
2
+ import { get } from 'svelte/store';
3
+
4
+ // TC-70: a plugin module without `panoSdk === 2` was built for @panomc/sdk 1.x and is skipped.
5
+
6
+ mock.module('$lib/api.util.js', () => ({ default: {} }));
7
+ mock.module('$lib/PluginAPI.js', () => ({ init: () => {}, panoApiClient: {}, panoApiServer: {} }));
8
+ mock.module('$app/env', () => ({ browser: false, dev: false }));
9
+ mock.module('$app/paths', () => ({ base: '' }));
10
+ mock.module('@sveltejs/kit', () => ({ error: (status) => new Error(`HTTP ${status}`) }));
11
+
12
+ const manager = await import('../PluginManager.js');
13
+
14
+ describe('dropOldSdkPlugins', () => {
15
+ test('a 1.x module is skipped with the rebuild message; a 2.x module stays', () => {
16
+ const spy = spyOn(console, 'error').mockImplementation(() => {});
17
+ manager.plugins.set({
18
+ old: { module: { default: class {} } },
19
+ wrong: { module: { default: class {}, panoSdk: 1 } },
20
+ fresh: { module: { default: class {}, panoSdk: 2 } },
21
+ unloaded: {},
22
+ });
23
+
24
+ const skipped = manager.dropOldSdkPlugins();
25
+ const messages = spy.mock.calls.map((call) => String(call[0]));
26
+ spy.mockRestore();
27
+
28
+ expect(skipped).toEqual(['old', 'wrong']);
29
+ expect(Object.keys(get(manager.plugins))).toEqual(['fresh', 'unloaded']);
30
+ expect(messages).toContain(
31
+ '[Plugin Manager] old was built for @panomc/sdk 1.x and does not load on this Pano; rebuild it with @panomc/plugin-kit',
32
+ );
33
+ });
34
+ });
@@ -0,0 +1,433 @@
1
+ import { API_URL, CSRF_HEADER } from "$lib/variables.js";
2
+ import { get } from "svelte/store";
3
+ import { page } from "./appStores.js";
4
+ import { browser } from "$app/env";
5
+ import { initialized } from "$lib/Store.js";
6
+ import { show } from "$lib/components/ToastContainer.svelte";
7
+
8
+ // Constants for network error handling
9
+ export const NETWORK_ERROR = 'NETWORK_ERROR';
10
+ export const networkErrorBody = { error: { code: NETWORK_ERROR } };
11
+ export const DISABLED_FOR_DEMO = 'DISABLED_FOR_DEMO';
12
+
13
+ /** Prefix of the whole API when the backend base (`API_URL`) ends in `/api` (doc 04 section 9). */
14
+ const API_VERSION_PREFIX = '/api/v1';
15
+
16
+ /** Prefix of the plugin namespace (decision 81): plugin endpoints are unversioned, `/api/plugins/<id>/...`. */
17
+ const API_PLUGIN_PREFIX = '/api';
18
+
19
+ const NETWORK_RETRY_DELAY_MS = 400;
20
+
21
+ function isIdempotent(method) {
22
+ return !method || ['GET', 'HEAD', 'OPTIONS'].includes(method.toUpperCase());
23
+ }
24
+
25
+ /**
26
+ * The browser's cached answer of `GET /auth/csrf` (doc 05 section 4): the promise of the token, `null`
27
+ * when the visitor has no cookie session. Kept in the browser only; on the server one module serves every
28
+ * visitor, so nothing is cached there.
29
+ * @type {Promise<string | null> | undefined}
30
+ */
31
+ let fetchedCsrfToken;
32
+
33
+ /** Forget the token fetched from `GET /auth/csrf` (a test, or a client that knows the session changed). */
34
+ export function resetFetchedCsrfToken() {
35
+ fetchedCsrfToken = undefined;
36
+ }
37
+
38
+ /**
39
+ * Ask Pano for the session's CSRF token. Used before a mutation when the page session has none (a front-end
40
+ * on another origin, or a page whose data carries no session): a cookie session answers `{ csrfToken }`, a
41
+ * Bearer or anonymous request gets `null` (`401` is "no live cookie session", not an error).
42
+ *
43
+ * @param {{ fetch?: typeof fetch } | undefined} request SvelteKit's `load` / event, whose `fetch` is used on the server
44
+ * @returns {Promise<string | null>}
45
+ */
46
+ async function loadCsrfToken(request) {
47
+ const url = resolveApiUrl('/auth/csrf', {
48
+ apiUrl: API_URL,
49
+ hasEventFetch: !!(request && request.fetch),
50
+ browser,
51
+ prod: !!import.meta.env.PROD,
52
+ });
53
+
54
+ try {
55
+ const response = await (request && request.fetch ? request.fetch : fetch)(url, {
56
+ credentials: 'include',
57
+ cache: 'no-store',
58
+ headers: { Accept: 'application/json' },
59
+ });
60
+
61
+ if (!response.ok) return null;
62
+
63
+ const body = await response.json();
64
+
65
+ return typeof body?.csrfToken === 'string' && body.csrfToken ? body.csrfToken : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /** The CSRF token for a mutation that has none: fetched once in the browser, per call on the server. */
72
+ function resolveCsrfToken(request) {
73
+ if (!browser) return loadCsrfToken(request);
74
+
75
+ fetchedCsrfToken ??= loadCsrfToken(request);
76
+
77
+ return fetchedCsrfToken;
78
+ }
79
+
80
+ /** A refused request means the session behind a cached token may be gone: ask again next time. */
81
+ function noteStatus(response) {
82
+ if (response && (response.status === 401 || response.status === 403)) fetchedCsrfToken = undefined;
83
+
84
+ return response;
85
+ }
86
+
87
+ // Function to build query parameters from an object
88
+ export function buildQueryParams(params) {
89
+ const queryString = Object.keys(params)
90
+ .filter((key) => params[key])
91
+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
92
+ .join('&');
93
+ return queryString === '' ? '' : '?' + queryString;
94
+ }
95
+
96
+ const isWebsiteApi = (apiUrl) => typeof apiUrl === 'string' && apiUrl.includes('.panomc.com');
97
+
98
+ const isLoopbackApi = (apiUrl) =>
99
+ typeof apiUrl === 'string' &&
100
+ (apiUrl.includes('0.0.0.0') || apiUrl.includes('127.0.0.1') || apiUrl.includes('localhost'));
101
+
102
+ /** A path that still carries the `/api` prefix (`/api`, `/api/...`, `/api?x`), but not `/apiary`. */
103
+ const startsWithApi = (path) => /^\/api(?:[/?#]|$)/.test(path);
104
+
105
+ /**
106
+ * A plugin's own endpoint path: `/plugins/<id>/...` or `/api/plugins/<id>/...`, anything but core's `/plugins/<id>/_/...`.
107
+ * These live outside `/api/v1` (decision 81), so `ApiUtil` sends them to `/api/plugins/<id>/...` whichever form came in.
108
+ * @param {string} path
109
+ */
110
+ export const isPluginOwnPath = (path) =>
111
+ typeof path === 'string' && /^\/(?:api\/)?plugins\/[^/?#]+\/(?!_(?:[/?#]|$))[^?#]/.test(path);
112
+
113
+ /**
114
+ * Callers pass paths relative to `/api/v1` ("/posts"). A missing leading slash is added.
115
+ * In dev a path that starts with `/api` throws (the website API has no `/v1`, so it is exempt).
116
+ *
117
+ * @param {string} path
118
+ * @param {{ website?: boolean, prod?: boolean }} [opts]
119
+ * @returns {string} the path with a leading slash
120
+ */
121
+ export function normalizeApiPath(path, { website = false, prod = false } = {}) {
122
+ if (typeof path !== 'string') throw new TypeError('[pano] api path must be a string');
123
+
124
+ const normalized = path.startsWith('/') ? path : `/${path}`;
125
+
126
+ if (!website && !prod && startsWithApi(normalized)) {
127
+ throw new Error(
128
+ `[pano] path must not start with /api: write '${normalized.replace(/^\/api/, '') || '/'}'`,
129
+ );
130
+ }
131
+
132
+ return normalized;
133
+ }
134
+
135
+ /**
136
+ * The URL of one call: exactly the four cases of doc 04 section 9, no pass-through.
137
+ *
138
+ * 1. `apiUrl` contains `.panomc.com` (the website; its API has no `/v1`): `apiUrl + path`.
139
+ * 2. `hasEventFetch` (SSR `load` behind the proxy): relative `/api/v1` + path, so SSR and CSR dedupe.
140
+ * 3. browser, and production or a loopback `apiUrl`: `/api/v1` + path.
141
+ * 4. everything else (SSR without an event, not initialised): `apiUrl + '/v1' + path`.
142
+ *
143
+ * With `unversioned` (a plugin's own endpoints, `/plugins/<id>/...`, decision 81) the same four cases apply but the
144
+ * version segment is left out: `/api` + path, or `apiUrl + path`.
145
+ *
146
+ * @param {string} path relative to `/api/v1` (relative to `/api` with `unversioned`)
147
+ * @param {{ apiUrl?: string, hasEventFetch?: boolean, browser?: boolean, prod?: boolean, unversioned?: boolean }} ctx
148
+ * @returns {string}
149
+ */
150
+ export function resolveApiUrl(
151
+ path,
152
+ { apiUrl = '', hasEventFetch = false, browser = false, prod = false, unversioned = false } = {},
153
+ ) {
154
+ const website = isWebsiteApi(apiUrl);
155
+ const relative = normalizeApiPath(path, { website, prod });
156
+ const root = unversioned ? API_PLUGIN_PREFIX : API_VERSION_PREFIX;
157
+
158
+ if (website) return `${apiUrl.replace(/\/+$/, '')}${relative}`;
159
+ if (hasEventFetch) return `${root}${relative}`;
160
+ if (browser && (prod || isLoopbackApi(apiUrl))) return `${root}${relative}`;
161
+
162
+ return `${(apiUrl || '/api').replace(/\/+$/, '')}${unversioned ? '' : '/v1'}${relative}`;
163
+ }
164
+
165
+ const ApiUtil = {
166
+ interceptors: {},
167
+
168
+ // GET request
169
+ async get({ path, request, csrfToken, token, blob, handler, unversioned }) {
170
+ return this.customRequest({
171
+ path,
172
+ unversioned,
173
+ request,
174
+ csrfToken,
175
+ token,
176
+ blob,
177
+ handler,
178
+ });
179
+ },
180
+
181
+ // POST request
182
+ async post({ path, request, body, headers, csrfToken, token, blob, handler, onUploadProgress, unversioned }) {
183
+ return this.customRequest({
184
+ path,
185
+ unversioned,
186
+ data: { method: 'POST', credentials: 'include', body, headers },
187
+ request,
188
+ csrfToken,
189
+ token,
190
+ blob,
191
+ handler,
192
+ onUploadProgress,
193
+ });
194
+ },
195
+
196
+ // PUT request
197
+ async put({ path, request, body, headers, csrfToken, token, blob, handler, onUploadProgress, unversioned }) {
198
+ return this.customRequest({
199
+ path,
200
+ unversioned,
201
+ data: { method: 'PUT', credentials: 'include', body, headers },
202
+ request,
203
+ csrfToken,
204
+ token,
205
+ blob,
206
+ handler,
207
+ onUploadProgress,
208
+ });
209
+ },
210
+
211
+ // DELETE request
212
+ async delete({ path, request, headers, csrfToken, token, blob, handler, unversioned }) {
213
+ return this.customRequest({
214
+ path,
215
+ unversioned,
216
+ data: { method: 'DELETE', headers },
217
+ request,
218
+ csrfToken,
219
+ token,
220
+ blob,
221
+ handler,
222
+ });
223
+ },
224
+
225
+ // Custom request handler
226
+ async customRequest({ path, data = {}, request, csrfToken, token, blob, handler, onUploadProgress, unversioned }) {
227
+ // Retrieve CSRF token if not provided
228
+ if (!csrfToken) {
229
+ let session;
230
+ if (request && typeof request.parent === "function") {
231
+ const parentData = await request.parent();
232
+ session = parentData.session;
233
+ } else if (browser && get(page).data) {
234
+ session = get(page).data.session;
235
+ }
236
+ csrfToken = session && session.csrfToken;
237
+ }
238
+
239
+ // A mutation on a cookie session needs the header (doc 05 section 4). When the page session has no token,
240
+ // ask `GET /auth/csrf` once. A Bearer call (`token`) never needs it.
241
+ if (!csrfToken && !token && !isIdempotent(data.method)) {
242
+ csrfToken = await resolveCsrfToken(request);
243
+ }
244
+
245
+ // Set CSRF header if token is available
246
+ const CSRFHeader = csrfToken ? { [CSRF_HEADER]: csrfToken } : {};
247
+
248
+ // Convert body to JSON string if not FormData
249
+ if (!(data.body instanceof FormData)) {
250
+ data.body = JSON.stringify(data.body);
251
+ data.headers = { 'Content-Type': 'application/json', ...data.headers };
252
+ }
253
+
254
+ // Set request options
255
+ const options = {
256
+ ...data,
257
+ headers: { ...data.headers, ...CSRFHeader },
258
+ };
259
+
260
+ // Add Authorization header if token is provided
261
+ if (token) {
262
+ options.headers['Authorization'] = `Bearer ${token}`;
263
+ } else if ('credentials' in Request.prototype) {
264
+ options['credentials'] = 'include';
265
+ }
266
+
267
+ // A plugin's own path (`/plugins/<id>/...`) is unversioned: `/api/plugins/<id>/...` (decision 81).
268
+ if (!unversioned && isPluginOwnPath(path)) {
269
+ unversioned = true;
270
+ path = path.replace(/^\/api(?=\/plugins\/)/, '');
271
+ }
272
+
273
+ // Callers pass paths relative to /api/v1; see resolveApiUrl for the four cases.
274
+ path = resolveApiUrl(path, {
275
+ apiUrl: API_URL,
276
+ hasEventFetch: !!(request && request.fetch),
277
+ browser,
278
+ prod: !!import.meta.env.PROD,
279
+ unversioned: !!unversioned,
280
+ });
281
+
282
+ const bodyHandler = (response) => (blob ? response.blob() : response.text());
283
+ const jsonParseHandler = (json) => {
284
+ try {
285
+ return JSON.parse(json);
286
+ } catch (err) {
287
+ return json;
288
+ }
289
+ };
290
+
291
+ const requestCall = (rejectHandler) => {
292
+ const reject = async (err) => {
293
+ console.log(err);
294
+ if (rejectHandler) {
295
+ throw new Error(err);
296
+ }
297
+
298
+ if (this.interceptors.errorHandler && handler) {
299
+ this.interceptors.errorHandler(requestCall);
300
+ }
301
+
302
+ // A failure without a response is an envelope too: callers read `error.code`.
303
+ return networkErrorBody;
304
+ };
305
+
306
+ if (onUploadProgress && browser && data.body instanceof FormData) {
307
+ return new Promise((resolve, rejectFn) => {
308
+ const xhr = new XMLHttpRequest();
309
+ xhr.open(data.method, path);
310
+
311
+ if (options.credentials === 'include') {
312
+ xhr.withCredentials = true;
313
+ }
314
+
315
+ const headersToSet = { ...options.headers };
316
+ delete headersToSet['Content-Type'];
317
+
318
+ Object.keys(headersToSet).forEach((key) => {
319
+ xhr.setRequestHeader(key, headersToSet[key]);
320
+ });
321
+
322
+ xhr.upload.onprogress = (event) => {
323
+ if (event.lengthComputable) {
324
+ onUploadProgress(event.loaded / event.total);
325
+ }
326
+ };
327
+
328
+ xhr.onload = async () => {
329
+ try {
330
+ let parsedJson;
331
+ try {
332
+ parsedJson = JSON.parse(xhr.responseText);
333
+ } catch (err) {
334
+ parsedJson = xhr.responseText;
335
+ }
336
+
337
+ if (parsedJson?.error?.code === DISABLED_FOR_DEMO) {
338
+ if (browser) {
339
+ await show("components.toasts.demo-mode-restricted");
340
+ }
341
+ resolve();
342
+ return;
343
+ }
344
+
345
+ const finalData = handler ? await handler(parsedJson, rejectFn) : parsedJson;
346
+ resolve(finalData);
347
+ } catch (err) {
348
+ rejectFn(err);
349
+ }
350
+ };
351
+
352
+ xhr.onerror = () => rejectFn(NETWORK_ERROR);
353
+
354
+ xhr.send(data.body);
355
+ }).catch(reject);
356
+ }
357
+
358
+ // Perform fetch request
359
+ const doFetch = () =>
360
+ (request && request.fetch ? request.fetch(path, options) : fetch(path, options)).then(noteStatus);
361
+
362
+ // A request that never got a response (fetch rejected) is retried ONCE before the
363
+ // offline splash: browsers reuse a pooled HTTP/3 connection that the peer may have
364
+ // just idled out (Firefox: 30 s), and the request on it fails instantly although the
365
+ // server is fine. A new connection succeeds. Only idempotent methods, so a POST/PUT
366
+ // is never sent twice; HTTP error responses are not retried (fetch resolves them).
367
+ const fetchMethod =
368
+ browser && isIdempotent(data.method)
369
+ ? doFetch().catch((err) => {
370
+ if (err?.name === 'AbortError') throw err;
371
+
372
+ return new Promise((resolve) => setTimeout(resolve, NETWORK_RETRY_DELAY_MS)).then(
373
+ doFetch,
374
+ );
375
+ })
376
+ : doFetch();
377
+
378
+ // Handle response
379
+ return fetchMethod
380
+ .then(bodyHandler)
381
+ .then(jsonParseHandler)
382
+ .then(async (parsedJson) => {
383
+ if (parsedJson?.error?.code === DISABLED_FOR_DEMO) {
384
+ if (browser) {
385
+ await show("components.toasts.demo-mode-restricted");
386
+ }
387
+ return;
388
+ }
389
+ return handler ? await handler(parsedJson, reject) : parsedJson;
390
+ })
391
+ .catch(reject);
392
+ };
393
+
394
+ return requestCall();
395
+ },
396
+ };
397
+
398
+ const PLUGIN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
399
+
400
+ /**
401
+ * Plugin-scoped client (doc 04 section 9). `createPluginApi('pano-plugin-market').get({ path: '/store/products' })`
402
+ * calls `/api/plugins/pano-plugin-market/store/products`; `.panel.get(...)` calls
403
+ * `/api/plugins/pano-plugin-market/panel/...` (decision 81: plugin endpoints are unversioned). Every method takes the options of the matching `ApiUtil` method.
404
+ * A path that starts with `/api` throws in dev, as it does for `ApiUtil`.
405
+ *
406
+ * @param {string} pluginId the full plugin id (`pano-plugin-market`), never the short namespace
407
+ */
408
+ export function createPluginApi(pluginId) {
409
+ if (typeof pluginId !== 'string' || !PLUGIN_ID_PATTERN.test(pluginId)) {
410
+ throw new Error(`[pano] createPluginApi needs the full plugin id, got ${JSON.stringify(pluginId)}`);
411
+ }
412
+
413
+ const scoped = (prefix) => {
414
+ const wrap = (method) => async (options = {}) =>
415
+ ApiUtil[method]({
416
+ ...options,
417
+ unversioned: true,
418
+ path: `${prefix}${normalizeApiPath(options.path, { prod: !!import.meta.env.PROD })}`,
419
+ });
420
+
421
+ return {
422
+ get: wrap('get'),
423
+ post: wrap('post'),
424
+ put: wrap('put'),
425
+ delete: wrap('delete'),
426
+ customRequest: wrap('customRequest'),
427
+ };
428
+ };
429
+
430
+ return { ...scoped(`/plugins/${pluginId}`), panel: scoped(`/plugins/${pluginId}/panel`) };
431
+ }
432
+
433
+ export default ApiUtil;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `page` and `navigating` as stores, in the shape SvelteKit 2's `$app/stores` had.
3
+ *
4
+ * SvelteKit 3 removed `$app/stores`; `$app/state` replaces it with rune-based objects whose changes the legacy
5
+ * (non-runes) syntax never sees. These stores read `$app/state`, so `$page` / `$navigating`, `get(page)` and `$:`
6
+ * statements keep working in legacy components and plain modules.
7
+ *
8
+ * On the server `$app/state` can only be read while rendering: a subscription (what `$page` makes during render) takes
9
+ * a snapshot then and never updates. In the browser the store follows the state.
10
+ *
11
+ * A plugin component is compiled with its own copy of Svelte's server runtime, and its `$page` can be read where the
12
+ * host's component context is not current (`$app/state` then throws). The host's app layout calls
13
+ * `captureRequestState()` while it renders, so such a read gets the page of the request being rendered (server
14
+ * rendering is synchronous: no other request runs in between).
15
+ */
16
+ import { navigating as navigatingState, page as pageState } from "$app/state";
17
+ import { browser } from "$app/env";
18
+ import { toStore } from "svelte/store";
19
+
20
+ function pageSnapshot() {
21
+ return {
22
+ url: pageState.url,
23
+ params: pageState.params,
24
+ route: pageState.route,
25
+ status: pageState.status,
26
+ error: pageState.error,
27
+ data: pageState.data,
28
+ form: pageState.form,
29
+ state: pageState.state,
30
+ };
31
+ }
32
+
33
+ /** `null` while no navigation runs, as the SvelteKit 2 store was. */
34
+ function navigatingSnapshot() {
35
+ const navigation = navigatingState;
36
+
37
+ if (!navigation.type) return null;
38
+
39
+ return {
40
+ from: navigation.from,
41
+ to: navigation.to,
42
+ type: navigation.type,
43
+ willUnload: navigation.willUnload,
44
+ delta: navigation.delta,
45
+ complete: navigation.complete,
46
+ };
47
+ }
48
+
49
+ /** The page of the request the server renders now (see `captureRequestState`). */
50
+ let requestPage = null;
51
+
52
+ /**
53
+ * Takes the page of the request being rendered; called by the host's app layout during its render on the server.
54
+ * A no-op in the browser.
55
+ */
56
+ export function captureRequestState() {
57
+ if (!browser) requestPage = pageSnapshot();
58
+ }
59
+
60
+ /**
61
+ * @template T
62
+ * @param {() => T} snapshot
63
+ * @param {() => T | null} fallback the server value when `$app/state` cannot be read here
64
+ * @returns {import("svelte/store").Readable<T>}
65
+ */
66
+ function stateStore(snapshot, fallback) {
67
+ /** @type {import("svelte/store").Readable<T> | undefined} */
68
+ let clientStore;
69
+
70
+ return {
71
+ subscribe(run, invalidate) {
72
+ if (!browser) {
73
+ let value;
74
+ try {
75
+ value = snapshot();
76
+ } catch (error) {
77
+ value = fallback();
78
+ if (value === null) throw error;
79
+ }
80
+ run(value);
81
+ return () => {};
82
+ }
83
+
84
+ clientStore ??= toStore(snapshot);
85
+
86
+ return clientStore.subscribe(run, invalidate);
87
+ },
88
+ };
89
+ }
90
+
91
+ export const page = stateStore(pageSnapshot, () => requestPage);
92
+ // never navigating while the server renders
93
+ export const navigating = stateStore(navigatingSnapshot, () => null);
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The app's base path: "" for a theme, "/panel" for panel-ui.
3
+ *
4
+ * SvelteKit 3 removed `base` from `$app/paths`. The engine's vite config (`createViteConfig`) defines
5
+ * `__PANO_BASE_PATH__` at build time with the value it gives SvelteKit as `paths.base`, so this is always the absolute
6
+ * path, on the server too (Pano serves every UI at a fixed path, so an absolute and a relative link point at the same
7
+ * place).
8
+ */
9
+ /* global __PANO_BASE_PATH__ */
10
+ export const base = typeof __PANO_BASE_PATH__ === "string" ? __PANO_BASE_PATH__ : "";
@@ -0,0 +1,26 @@
1
+ const ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
2
+
3
+ /**
4
+ * Escapes the five HTML special characters.
5
+ * @param {unknown} s
6
+ * @returns {string}
7
+ */
8
+ export function escapeHtml(s) {
9
+ return String(s).replace(/[&<>"']/g, (c) => ESCAPES[c]);
10
+ }
11
+
12
+ /**
13
+ * Shallow copy of `values` with string values HTML-escaped; other values are untouched.
14
+ * A non-object yields `{}`.
15
+ * @param {unknown} values
16
+ * @returns {Record<string, unknown>}
17
+ */
18
+ export function escapeValues(values) {
19
+ if (values === null || typeof values !== 'object' || Array.isArray(values)) return {};
20
+
21
+ const out = {};
22
+ for (const [k, v] of Object.entries(values)) {
23
+ out[k] = typeof v === 'string' ? escapeHtml(v) : v;
24
+ }
25
+ return out;
26
+ }