@panomc/sdk 1.0.0-dev.4 → 1.0.0-dev.40

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 (85) hide show
  1. package/README.md +3 -3
  2. package/core/favicon/apple-touch-icon.png +0 -0
  3. package/core/favicon/favicon-96x96.png +0 -0
  4. package/core/favicon/favicon.ico +0 -0
  5. package/core/favicon/favicon.svg +1 -0
  6. package/core/favicon/site.webmanifest +21 -0
  7. package/core/favicon/web-app-manifest-192x192.png +0 -0
  8. package/core/favicon/web-app-manifest-512x512.png +0 -0
  9. package/core/favicon_old/android-icon-144x144.png +0 -0
  10. package/core/favicon_old/android-icon-192x192.png +0 -0
  11. package/core/favicon_old/android-icon-36x36.png +0 -0
  12. package/core/favicon_old/android-icon-48x48.png +0 -0
  13. package/core/favicon_old/android-icon-72x72.png +0 -0
  14. package/core/favicon_old/android-icon-96x96.png +0 -0
  15. package/core/favicon_old/apple-icon-114x114.png +0 -0
  16. package/core/favicon_old/apple-icon-120x120.png +0 -0
  17. package/core/favicon_old/apple-icon-144x144.png +0 -0
  18. package/core/favicon_old/apple-icon-152x152.png +0 -0
  19. package/core/favicon_old/apple-icon-180x180.png +0 -0
  20. package/core/favicon_old/apple-icon-57x57.png +0 -0
  21. package/core/favicon_old/apple-icon-60x60.png +0 -0
  22. package/core/favicon_old/apple-icon-72x72.png +0 -0
  23. package/core/favicon_old/apple-icon-76x76.png +0 -0
  24. package/core/favicon_old/apple-icon-precomposed.png +0 -0
  25. package/core/favicon_old/apple-icon.png +0 -0
  26. package/core/favicon_old/browserconfig.xml +11 -0
  27. package/core/favicon_old/favicon-16x16.png +0 -0
  28. package/core/favicon_old/favicon-32x32.png +0 -0
  29. package/core/favicon_old/favicon-96x96.png +0 -0
  30. package/core/favicon_old/favicon.ico +0 -0
  31. package/core/favicon_old/manifest.json +41 -0
  32. package/core/favicon_old/ms-icon-144x144.png +0 -0
  33. package/core/favicon_old/ms-icon-150x150.png +0 -0
  34. package/core/favicon_old/ms-icon-310x310.png +0 -0
  35. package/core/favicon_old/ms-icon-70x70.png +0 -0
  36. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.eot +0 -0
  37. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.svg +483 -0
  38. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.ttf +0 -0
  39. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff +0 -0
  40. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-300.woff2 +0 -0
  41. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.eot +0 -0
  42. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.svg +486 -0
  43. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.ttf +0 -0
  44. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff +0 -0
  45. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-500.woff2 +0 -0
  46. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.eot +0 -0
  47. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.svg +484 -0
  48. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.ttf +0 -0
  49. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff +0 -0
  50. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-700.woff2 +0 -0
  51. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.eot +0 -0
  52. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.svg +486 -0
  53. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.ttf +0 -0
  54. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff +0 -0
  55. package/core/fonts/quicksand-v8-latin-ext_latin_vietnamese-regular.woff2 +0 -0
  56. package/core/js/NotificationManager.js +19 -0
  57. package/core/js/PluginAPI.js +29 -0
  58. package/core/js/PluginManager.js +789 -0
  59. package/core/js/RouteMatcher.js +134 -0
  60. package/core/js/api.util.js +248 -0
  61. package/core/js/tooltip.util.js +59 -0
  62. package/core/js/variables.js +60 -0
  63. package/core/js/version.util.js +100 -0
  64. package/core/scss/custom-bootstrap.scss +187 -0
  65. package/core/scss/fonts.scss +85 -0
  66. package/core/scss/main.scss +385 -0
  67. package/core/scss/themes.scss +97 -0
  68. package/package.json +34 -10
  69. package/src/api/plugin-context.js +3 -3
  70. package/src/api/plugin.js +20 -3
  71. package/src/components/{index.js → panel.js} +12 -8
  72. package/src/components/theme.js +13 -0
  73. package/src/index.js +3 -3
  74. package/src/internal/index.js +1 -1
  75. package/src/internal/pano-context.js +14 -4
  76. package/src/svelte.js +7 -0
  77. package/src/toasts/index.js +2 -2
  78. package/src/types.js +40 -0
  79. package/src/utils/api.js +2 -2
  80. package/src/utils/auth.js +8 -0
  81. package/src/utils/component.js +11 -9
  82. package/src/utils/language.js +3 -1
  83. package/src/utils/text.js +8 -0
  84. package/src/utils/tooltip.js +1 -1
  85. package/src/variables.js +1 -1
@@ -0,0 +1,789 @@
1
+ import fs from "fs";
2
+
3
+ import { error as httpError } from "@sveltejs/kit";
4
+ import { browser, dev } from "$app/environment";
5
+ import { get, writable } from "svelte/store";
6
+ import ApiUtil from "$lib/api.util.js";
7
+ import { base } from "$app/paths";
8
+
9
+ import { init as initPluginAPI, panoApiClient, panoApiServer } from "$lib/PluginAPI.js";
10
+ import { PanoPlugin } from "@panomc/sdk";
11
+ import { findMatch } from "./RouteMatcher.js";
12
+
13
+ export let registeredPages = {};
14
+
15
+ export { findMatch };
16
+
17
+ let path, url, admZip;
18
+
19
+ let serverSidePrepared = false;
20
+ let serverSideInitialized = false;
21
+ let lastProcessedBackendHash = null;
22
+ let lastProcessedFrontendHash = null;
23
+ let clientSideInitialized = false;
24
+ let clientSidePluginHash = null;
25
+
26
+ // In-flight preparePlugins promise. Filesystem mutations in verifyPlugins are not safe to
27
+ // interleave between concurrent SSR requests; concurrent runs were producing partial states
28
+ // where some files were being deleted while others were being read.
29
+ let preparePluginsInflight = null;
30
+
31
+ // In-flight initializePlugins promise, keyed by the frontend plugin hash it is building for.
32
+ // Without it, concurrent SSR requests each reset the shared module-global stores (registeredPages,
33
+ // livePluginInstances, the plugins store) mid-flight, racing each other into torn/blank plugin UI,
34
+ // double onLoad calls and transient false 404s. Claimed synchronously before any await.
35
+ let initializePluginsInflight = null;
36
+ let initializePluginsInflightHash = null;
37
+
38
+
39
+
40
+ if (!browser) {
41
+ const pathStuff = await import('path');
42
+ const urlStuff = await import('url');
43
+ const admZipStuff = await import('adm-zip');
44
+
45
+ path = pathStuff;
46
+ url = urlStuff;
47
+ admZip = admZipStuff.default;
48
+ }
49
+
50
+ export const plugins = writable({});
51
+
52
+ const pluginsFolder = 'plugins';
53
+ const manifestFileName = 'manifest.json';
54
+ const pluginUiZipFileName = 'plugin-ui.zip';
55
+
56
+ function log(message) {
57
+ if (dev) console.log(`[Plugin Manager] ${message}`);
58
+ }
59
+
60
+ function error(message) {
61
+ if (dev) console.error(`[Plugin Manager] ${message}`);
62
+ }
63
+
64
+ function debug(message) {
65
+ if (dev) console.debug(`[Plugin Manager] ${message}`);
66
+ }
67
+
68
+ function createPluginsFolder() {
69
+ if (!fs.existsSync(pluginsFolder)) {
70
+ fs.mkdirSync(pluginsFolder, { recursive: true });
71
+ }
72
+ }
73
+
74
+ function isDirectory(path) {
75
+ try {
76
+ return fs.statSync(path).isDirectory();
77
+ } catch (error) {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ async function downloadAndExtractZip(file, outputDir) {
83
+ const arrayBuffer = await file.arrayBuffer();
84
+ const buffer = Buffer.from(arrayBuffer);
85
+ const zip = new admZip(buffer, {});
86
+
87
+ zip.extractAllTo(outputDir, true);
88
+ }
89
+
90
+ function readPluginsFromFolder(siteInfo) {
91
+ const readPluginsFolder = fs.readdirSync(pluginsFolder);
92
+
93
+ const plugins = {};
94
+
95
+ readPluginsFolder
96
+ .filter((pluginId) => isDirectory(path.join(pluginsFolder, pluginId)))
97
+ .forEach((pluginId) => {
98
+ try {
99
+ const manifestFile = fs.readFileSync(path.join(pluginsFolder, pluginId, manifestFileName), {
100
+ encoding: 'utf8',
101
+ flag: 'r',
102
+ });
103
+
104
+ plugins[pluginId] = JSON.parse(manifestFile);
105
+ } catch (_) {
106
+ // if (siteInfo.developmentMode) {
107
+ // plugins[pluginId] = {
108
+ // version: 'dev-build',
109
+ // uiHash: 'dev-build',
110
+ // };
111
+ // }
112
+ }
113
+ });
114
+
115
+ return plugins;
116
+ }
117
+
118
+ async function downloadPluginUiZip(pluginId) {
119
+ return await ApiUtil.get({
120
+ path: `/api/plugins/${pluginId}/resources/${pluginUiZipFileName}`,
121
+ blob: true,
122
+ });
123
+ }
124
+
125
+ // A plugin folder counts as "intact" only if all three pieces produced by a real install
126
+ // are present: the root manifest.json and both the server/ and client/ subdirs. Anything
127
+ // else is a shell folder — left over from a download that 404'd, an extraction that
128
+ // produced an empty zip, an update that swapped out the old subdirs and then couldn't
129
+ // move new ones in, or a crashed install/update where the staging dir never got renamed
130
+ // into place. We need to recognize and purge these eagerly: readPluginsFromFolder silently
131
+ // drops them (manifest read fails → not in pluginsInFolder), so they slip past the rest
132
+ // of verifyPlugins and then make the install path's existsSync check think the plugin
133
+ // is "already there", which discards the fresh download.
134
+ function isPluginFolderIntact(pluginFolder) {
135
+ return (
136
+ fs.existsSync(path.join(pluginFolder, manifestFileName)) &&
137
+ isDirectory(path.join(pluginFolder, 'server')) &&
138
+ isDirectory(path.join(pluginFolder, 'client'))
139
+ );
140
+ }
141
+
142
+ function purgeIncompletePluginFolders() {
143
+ let entries;
144
+ try {
145
+ entries = fs.readdirSync(pluginsFolder);
146
+ } catch {
147
+ return;
148
+ }
149
+
150
+ entries.forEach((entry) => {
151
+ const entryPath = path.join(pluginsFolder, entry);
152
+ if (!isDirectory(entryPath)) return;
153
+
154
+ // Stale staging dirs from a previous crashed install/update (".pluginId.install.<pid>.<ts>"
155
+ // / ".pluginId.update.<pid>.<ts>"). The preparePluginsInflight lock guarantees no
156
+ // install is running in parallel with verifyPlugins, so any leading-dot dir here is
157
+ // dead and safe to remove.
158
+ if (entry.startsWith('.')) {
159
+ log(`Removing stale staging dir '${entry}'...`);
160
+ fs.rmSync(entryPath, { recursive: true, force: true });
161
+ return;
162
+ }
163
+
164
+ if (!isPluginFolderIntact(entryPath)) {
165
+ log(`Removing incomplete plugin folder '${entry}'...`);
166
+ fs.rmSync(entryPath, { recursive: true, force: true });
167
+ // Also drop it from the live store if a previous run added it there.
168
+ plugins.update((p) => {
169
+ delete p[entry];
170
+ return p;
171
+ });
172
+ }
173
+ });
174
+ }
175
+
176
+ async function verifyPlugins(siteInfo) {
177
+ // this method is fully BFF (backend for front-end) SSR
178
+
179
+ const pluginsInfo = siteInfo.plugins;
180
+
181
+ // Phase 0: scrub any shell/staging folders before we trust readPluginsFromFolder's view.
182
+ // Doing this up front means the rest of verifyPlugins operates on a known-clean disk,
183
+ // which kills the failure mode where a half-installed folder kept making the install
184
+ // path's existsSync check throw away every fresh download. The caller's
185
+ // pluginsInFolder snapshot is discarded — we re-read after purge.
186
+ purgeIncompletePluginFolders();
187
+
188
+ const pluginsInFolder = readPluginsFromFolder(siteInfo);
189
+ const pluginIdInFolderList = Object.keys(pluginsInFolder);
190
+
191
+ // After Phase 0 every folder on disk is intact (manifest + server/ + client/), so
192
+ // pluginIdInFolderList only contains plugins we can trust. The legacy "fix broken
193
+ // folder" pass that used to live here is now redundant — Phase 0 covers every shape
194
+ // of brokenness it tried to repair, and does so before we trust the snapshot.
195
+ pluginIdInFolderList.forEach((pluginId) => {
196
+ // Wipe plugins the BE no longer reports (disabled, uninstalled, lost license, etc.).
197
+ if (!pluginsInfo[pluginId]) {
198
+ log(`Removing '${pluginId}' folder...`);
199
+
200
+ fs.rmSync(path.join(pluginsFolder, pluginId), {
201
+ recursive: true,
202
+ force: true,
203
+ });
204
+
205
+ plugins.update((p) => {
206
+ delete p[pluginId];
207
+ return p;
208
+ });
209
+ return;
210
+ }
211
+
212
+ // Plugin is intact on disk and still wanted by the BE — surface it via the store.
213
+ //
214
+ // Dev mode used to WIPE every folder here on every SSR pass so `bun dev` rebuilds
215
+ // reach the page without needing the BE-side uiHash to roll. That opened a window
216
+ // spanning the whole re-download in which /plugins/<id>/resources/... 404'd: any
217
+ // browser module fetch racing an SSR pass failed, and when its one cache-busted
218
+ // retry landed in the same window the plugin was dropped for the entire session
219
+ // (page renders via SSR, then loses every plugin UI at CSR). Instead, poison the
220
+ // stored uiHash so the update pass below re-downloads just as eagerly, but through
221
+ // downloadAndInstallPlugin's staged download + atomic rename — the old build keeps
222
+ // serving until the new one is in place, so the missing-folder window collapses
223
+ // from ~download-time to the two-rename instant (which the browser-side
224
+ // cache-busted retry already absorbs).
225
+ plugins.update((p) => {
226
+ p[pluginId] = siteInfo.developmentMode
227
+ ? { ...pluginsInFolder[pluginId], uiHash: `dev-stale-${Date.now()}` }
228
+ : pluginsInFolder[pluginId];
229
+ return p;
230
+ });
231
+ });
232
+
233
+ // Drop store entries the current pluginIdInFolderList no longer backs (e.g. left
234
+ // over from a previous run before Phase 0 deleted the underlying folder).
235
+ Object.keys(get(plugins))
236
+ .filter((pluginId) => !pluginIdInFolderList.includes(pluginId))
237
+ .forEach((pluginId) => {
238
+ log(`Removing plugin '${pluginId}'...`);
239
+
240
+ plugins.update((p) => {
241
+ delete p[pluginId];
242
+ return p;
243
+ });
244
+ });
245
+
246
+ // Install plugin if it exists in pluginsInfo (BE) and not installed
247
+ const notInstalledPlugins = Object.keys(pluginsInfo).filter(
248
+ // this prevents it must be enabled and loaded in BE, otherwise UI is null
249
+ (pluginId) => !get(plugins)[pluginId],
250
+ );
251
+
252
+ await Promise.all(
253
+ notInstalledPlugins.map((pluginId) =>
254
+ downloadAndInstallPlugin(pluginId, pluginsInfo[pluginId], 'install'),
255
+ ),
256
+ );
257
+
258
+ // Update plugins whose on-disk version/uiHash doesn't match what the backend now serves.
259
+ // This is where dev-mode `bun dev` rebuilds get picked up (BE bumps the hash, we re-fetch).
260
+ await Promise.all(
261
+ Object.keys(get(plugins)).map(async (pluginId) => {
262
+ const pluginInfoManifest = pluginsInfo[pluginId];
263
+ if (!pluginInfoManifest) return;
264
+
265
+ const pluginManifest = get(plugins)[pluginId];
266
+ if (
267
+ pluginManifest.version === pluginInfoManifest.version &&
268
+ pluginManifest.uiHash === pluginInfoManifest.uiHash
269
+ ) {
270
+ return;
271
+ }
272
+
273
+ await downloadAndInstallPlugin(pluginId, pluginInfoManifest, 'update');
274
+ }),
275
+ );
276
+ }
277
+
278
+ /**
279
+ * Download the plugin-ui.zip for a plugin and atomically replace its folder with the new
280
+ * content. Used for both first-time installs and updates — the two used to have separate
281
+ * code paths and the update path's per-subdir swap could leave the folder as a manifest-
282
+ * only shell when the downloaded zip was malformed (no server/ or no client/ inside).
283
+ * One code path means one set of invariants to enforce.
284
+ *
285
+ * Invariant after a successful return: pluginFolder contains manifest.json + server/ +
286
+ * client/, and the `plugins` store entry matches what's on disk.
287
+ *
288
+ * On any failure (download error, malformed zip, missing server/ or client/, fs error)
289
+ * we leave the previous on-disk state untouched (so an old working build keeps serving)
290
+ * and drop the plugin from the store so the rest of the SSR pass and the browser-side
291
+ * loader skip it cleanly instead of trying to import files that don't exist. The
292
+ * `bun dev` workflow is unaffected: BE bumps the uiHash on rebuild, this function runs,
293
+ * and the new build replaces the old one wholesale.
294
+ */
295
+ async function downloadAndInstallPlugin(pluginId, pluginManifest, mode) {
296
+ const pluginFolder = path.join(pluginsFolder, pluginId);
297
+ const tmpDir = path.join(pluginsFolder, `.${pluginId}.${mode}.${process.pid}.${Date.now()}`);
298
+
299
+ log(`${mode === 'install' ? 'Installing' : 'Updating'} plugin '${pluginId}'...`);
300
+ log(`Downloading '${pluginId}'...`);
301
+
302
+ try {
303
+ const file = await downloadPluginUiZip(pluginId);
304
+ await downloadAndExtractZip(file, tmpDir);
305
+
306
+ // Skip plugins whose download didn't yield a valid UI build. This is the symptom of
307
+ // either a 404/empty response that adm-zip didn't reject, or a publisher mistake.
308
+ // Either way we don't want to commit a manifest-only shell folder to disk.
309
+ if (
310
+ !isDirectory(path.join(tmpDir, 'server')) ||
311
+ !isDirectory(path.join(tmpDir, 'client'))
312
+ ) {
313
+ fs.rmSync(tmpDir, { recursive: true, force: true });
314
+ error(`Plugin '${pluginId}' download is missing server/ or client/ — skipping.`);
315
+ plugins.update((p) => {
316
+ delete p[pluginId];
317
+ return p;
318
+ });
319
+ return;
320
+ }
321
+
322
+ fs.writeFileSync(path.join(tmpDir, manifestFileName), JSON.stringify(pluginManifest, null, 2));
323
+
324
+ // Full-folder swap: rm-rf the old (Phase 0 already removed anything broken; the only
325
+ // case `pluginFolder` exists here is a clean update), then rename our staged dir in.
326
+ // The window where pluginFolder is briefly missing is the two-rename interval —
327
+ // microseconds — and Phase 0 + the inflight lock guarantee nothing else is reading
328
+ // mid-swap from SSR. Browser-side imports race against rename naturally; if one
329
+ // lands in the gap it 404s, and the PluginManager's reload-once retry resolves it.
330
+ fs.rmSync(pluginFolder, { recursive: true, force: true });
331
+ fs.renameSync(tmpDir, pluginFolder);
332
+
333
+ plugins.update((p) => {
334
+ p[pluginId] = structuredClone(pluginManifest);
335
+ return p;
336
+ });
337
+
338
+ log(`'${pluginId}' successfully ${mode === 'install' ? 'installed' : 'updated'}.`);
339
+ } catch (e) {
340
+ fs.rmSync(tmpDir, { recursive: true, force: true });
341
+ error(`Failed to ${mode} plugin '${pluginId}': ${e?.message ?? e}`);
342
+ // Don't surface the error: a single bad plugin must not break SSR for the rest of
343
+ // the panel. Drop the entry so downstream code doesn't try to load it.
344
+ plugins.update((p) => {
345
+ delete p[pluginId];
346
+ return p;
347
+ });
348
+ }
349
+ }
350
+
351
+ export async function preparePlugins(siteInfo) {
352
+ // The backend is the source of truth for the plugin set. While it is unreachable
353
+ // (still booting, restarting, crashed) siteInfo arrives undefined/empty — fail with a
354
+ // real 503 instead of a TypeError-turned-500 with a stack trace, so proxies and
355
+ // monitoring see "temporarily unavailable" and the first request after the backend
356
+ // returns recovers normally.
357
+ if (!siteInfo || typeof siteInfo !== "object" || !siteInfo.plugins) {
358
+ throw httpError(503, "Pano backend is not reachable yet");
359
+ }
360
+
361
+ const currentBackendHash = JSON.stringify(siteInfo.plugins);
362
+
363
+ // Loop so that after awaiting another request's preparation we recheck the cache: it may
364
+ // have produced the state we need (then we exit immediately), or it may have produced a
365
+ // different state (then we claim a fresh run).
366
+ while (true) {
367
+ if (preparePluginsInflight) {
368
+ try { await preparePluginsInflight; } catch { /* the owner re-throws to its caller */ }
369
+ continue;
370
+ }
371
+
372
+ const isCacheHit = !browser && !siteInfo.developmentMode && serverSidePrepared && lastProcessedBackendHash === currentBackendHash;
373
+ if (isCacheHit) break;
374
+
375
+ // Claim the lock synchronously before any await — otherwise two callers can both observe
376
+ // `preparePluginsInflight === null` and race.
377
+ preparePluginsInflight = (async () => {
378
+ createPluginsFolder();
379
+ await verifyPlugins(siteInfo);
380
+ if (!browser) {
381
+ serverSidePrepared = true;
382
+ lastProcessedBackendHash = currentBackendHash;
383
+ }
384
+ })();
385
+ try {
386
+ await preparePluginsInflight;
387
+ } finally {
388
+ preparePluginsInflight = null;
389
+ }
390
+ break;
391
+ }
392
+
393
+ const newSiteInfoPlugins = {};
394
+ const loadedPlugins = get(plugins);
395
+ Object.keys(loadedPlugins).forEach((pluginId) => {
396
+ const plugin = loadedPlugins[pluginId];
397
+ // In some versions version is an object containing metadata, in others it's directly on the plugin.
398
+ const vObj = plugin.version;
399
+ const { version, uiHash } = (vObj && typeof vObj === 'object') ? vObj : plugin;
400
+ const deps = plugin.dependencies;
401
+ newSiteInfoPlugins[pluginId] = { version, uiHash, ...(deps ? { dependencies: deps } : {}) };
402
+ });
403
+ siteInfo.plugins = newSiteInfoPlugins;
404
+ }
405
+
406
+
407
+ function generateStablePluginHash(siteInfoPlugins) {
408
+ const stableData = {};
409
+ // Sort plugin ids so the hash is independent of object iteration order.
410
+ for (const id of Object.keys(siteInfoPlugins || {}).sort()) {
411
+ const plugin = siteInfoPlugins[id];
412
+ const vObj = plugin.version;
413
+ const { version, uiHash } = (vObj && typeof vObj === "object") ? vObj : plugin;
414
+ // Include dependencies (load-order relevant): a dep-only change must invalidate the init
415
+ // cache, otherwise the topological load order can go stale while version/uiHash are equal.
416
+ // Normalize to a sorted array so the dep set — not its declaration order — is what matters.
417
+ const deps = Array.isArray(plugin.dependencies) ? [...plugin.dependencies].sort() : [];
418
+ stableData[id] = { version, uiHash, dependencies: deps };
419
+ }
420
+ return JSON.stringify(stableData);
421
+ }
422
+
423
+ // Live plugin instances on the client. Re-init calls __destroy() on these so a
424
+ // plugin's onUnload runs and any subscriptions it registered via this._unsubscribers
425
+ // get cleaned up before its next onLoad (or before it disappears on disable/remove).
426
+ const livePluginInstances = new Map();
427
+
428
+ async function destroyLivePluginInstances() {
429
+ if (livePluginInstances.size === 0) return;
430
+ const entries = Array.from(livePluginInstances.entries());
431
+ livePluginInstances.clear();
432
+ await Promise.allSettled(
433
+ entries.map(async ([pluginId, instance]) => {
434
+ try {
435
+ await instance.__destroy?.();
436
+ } catch (e) {
437
+ if (dev) console.error(`[PluginManager] __destroy failed for ${pluginId}:`, e);
438
+ }
439
+ })
440
+ );
441
+ }
442
+
443
+ function isInitializeCacheHit(siteInfo, currentFrontendHash) {
444
+ // SSR cache: skip if already initialized with the same plugin set
445
+ if (!browser && !siteInfo.developmentMode && serverSideInitialized && lastProcessedFrontendHash === currentFrontendHash) {
446
+ return true;
447
+ }
448
+ // Client-side cache: skip if already initialized with the same plugin set
449
+ if (browser && clientSideInitialized && clientSidePluginHash === currentFrontendHash) {
450
+ return true;
451
+ }
452
+ return false;
453
+ }
454
+
455
+ async function doInitializePlugins(siteInfo, currentFrontendHash) {
456
+ // Build the new route table in a LOCAL map and swap the live binding atomically once it is
457
+ // fully populated, instead of clearing the live `registeredPages` and rebuilding it in place.
458
+ // Plugins register into the live binding from their onLoad (via PluginAPI), so we point it at
459
+ // the fresh map for the duration of the build and only ever expose a complete table — a
460
+ // reader (findMatch) racing a rebuild sees either the old complete table or the new complete
461
+ // one, never a half-cleared one.
462
+ const previousRegisteredPages = registeredPages;
463
+ const newRegisteredPages = {};
464
+ registeredPages = newRegisteredPages;
465
+
466
+ try {
467
+ if (browser) {
468
+ await destroyLivePluginInstances();
469
+ }
470
+
471
+ await initPluginAPI();
472
+
473
+ if (browser) {
474
+ const pluginsInfo = siteInfo.plugins;
475
+
476
+ plugins.set(pluginsInfo);
477
+ }
478
+
479
+ await loadPlugins(siteInfo);
480
+ } catch (e) {
481
+ // On failure, restore the previous complete table so we don't leave a partial one live.
482
+ registeredPages = previousRegisteredPages;
483
+ throw e;
484
+ }
485
+
486
+ if (!browser) {
487
+ serverSideInitialized = true;
488
+ lastProcessedFrontendHash = currentFrontendHash;
489
+ } else {
490
+ clientSideInitialized = true;
491
+ clientSidePluginHash = currentFrontendHash;
492
+ }
493
+ }
494
+
495
+ export async function initializePlugins(siteInfo) {
496
+ const currentFrontendHash = generateStablePluginHash(siteInfo.plugins);
497
+
498
+ // Loop so that after awaiting another request's in-flight init we recheck the cache: it may
499
+ // have produced exactly the state we need (exit), or a different one (claim a fresh run).
500
+ while (true) {
501
+ if (isInitializeCacheHit(siteInfo, currentFrontendHash)) return;
502
+
503
+ if (initializePluginsInflight) {
504
+ // Someone is already initializing. If it's for our hash, just await it and we're done;
505
+ // otherwise await it and re-loop to claim our own run against the now-settled state.
506
+ const sameHash = initializePluginsInflightHash === currentFrontendHash;
507
+ try { await initializePluginsInflight; } catch { /* the owner re-throws to its caller */ }
508
+ if (sameHash && isInitializeCacheHit(siteInfo, currentFrontendHash)) return;
509
+ continue;
510
+ }
511
+
512
+ // Claim the lock synchronously before any await — otherwise two callers can both observe
513
+ // `initializePluginsInflight === null` and race, each resetting the shared stores.
514
+ initializePluginsInflightHash = currentFrontendHash;
515
+ initializePluginsInflight = doInitializePlugins(siteInfo, currentFrontendHash);
516
+ try {
517
+ await initializePluginsInflight;
518
+ } finally {
519
+ initializePluginsInflight = null;
520
+ initializePluginsInflightHash = null;
521
+ }
522
+ return;
523
+ }
524
+ }
525
+
526
+
527
+ const moduleCache = new Map();
528
+
529
+ function buildPluginDependencyGraph(loadedPlugins) {
530
+ const pluginIds = new Set(Object.keys(loadedPlugins));
531
+ const graph = {};
532
+ for (const pluginId of pluginIds) {
533
+ const plugin = loadedPlugins[pluginId];
534
+ // Only include dependencies that are actually loaded
535
+ const deps = (plugin.dependencies || []).filter(dep => pluginIds.has(dep));
536
+ graph[pluginId] = deps;
537
+ }
538
+ return graph;
539
+ }
540
+
541
+ function topologicalSortPlugins(graph) {
542
+ const inDegree = {};
543
+ const adj = {};
544
+
545
+ for (const node of Object.keys(graph)) {
546
+ if (!(node in inDegree)) inDegree[node] = 0;
547
+ if (!(node in adj)) adj[node] = [];
548
+ }
549
+
550
+ for (const [node, deps] of Object.entries(graph)) {
551
+ for (const dep of deps) {
552
+ if (!(dep in adj)) {
553
+ adj[dep] = [];
554
+ }
555
+ if (!(dep in inDegree)) inDegree[dep] = 0;
556
+ adj[dep].push(node);
557
+ inDegree[node] = (inDegree[node] || 0) + 1;
558
+ }
559
+ }
560
+
561
+ const levels = [];
562
+ let queue = Object.keys(inDegree).filter(n => inDegree[n] === 0);
563
+
564
+ while (queue.length > 0) {
565
+ levels.push([...queue]);
566
+ const nextQueue = [];
567
+ for (const node of queue) {
568
+ for (const neighbor of (adj[node] || [])) {
569
+ inDegree[neighbor]--;
570
+ if (inDegree[neighbor] === 0) nextQueue.push(neighbor);
571
+ }
572
+ }
573
+ queue = nextQueue;
574
+ }
575
+
576
+ // Fallback: if circular deps prevent resolution, run remaining plugins
577
+ const resolved = new Set(levels.flat());
578
+ const unresolved = Object.keys(graph).filter(n => !resolved.has(n));
579
+ if (unresolved.length > 0) {
580
+ levels.push(unresolved);
581
+ }
582
+
583
+ return levels;
584
+ }
585
+
586
+ async function loadPlugins(siteInfo) {
587
+ // Phase 1: Import all plugin modules in parallel for faster loading
588
+ const pluginIds = Object.keys(get(plugins));
589
+
590
+ await Promise.all(
591
+ pluginIds.map(async (pluginId) => {
592
+ const plugin = get(plugins)[pluginId];
593
+ if (!plugin) return;
594
+
595
+ if (browser) {
596
+ // The `?v=<uiHash>` segment is what gives this URL meaning as a content identifier:
597
+ // the browser module cache is keyed by URL, so distinct hashes get distinct cache
598
+ // entries. Without this, a plugin update mutates server-side files but the browser
599
+ // keeps using the old module from its cache for the rest of the session.
600
+ const uiHashSuffix = plugin.uiHash ? `?v=${plugin.uiHash}` : '';
601
+ const reloadKey = `pano:plugin-reload:${pluginId}:${plugin.uiHash || 'no-hash'}`;
602
+ const moduleUrl = `${base}/plugins/${pluginId}/resources/plugin-ui/client/client.mjs${uiHashSuffix}`;
603
+ // Permanent, deterministic failures where re-fetching the exact same bytes fails
604
+ // identically forever — reloading is useless and punishes every fresh tab:
605
+ // - SyntaxError / "does not provide an export named …" / "is not a module":
606
+ // the plugin was built against a different svelte/SDK (ABI/version skew).
607
+ // - "Failed to resolve module specifier" (Chrome) / "was a bare specifier" (Firefox)
608
+ // / "does not resolve to a valid URL" (Safari): the plugin imports a bare
609
+ // specifier absent from the host import map — resolution never touches the
610
+ // network, so retry and reload cannot change the outcome.
611
+ // - "[pano-runtime] …": the host runtime registry rejected the specifier.
612
+ const isVersionSkewError = (err) =>
613
+ err instanceof SyntaxError ||
614
+ /does not provide an export named|is not a module|Unexpected (token|reserved word|end of input)|Failed to resolve module specifier|bare specifier|does not resolve to a valid URL|pano-runtime/i.test(
615
+ String(err?.message ?? err),
616
+ );
617
+ try {
618
+ try {
619
+ plugin.module = await import(/* @vite-ignore */ moduleUrl);
620
+ } catch (firstError) {
621
+ if (isVersionSkewError(firstError)) throw firstError;
622
+ // A failed module fetch is cached in the document's module map (per HTML
623
+ // spec) — re-importing the SAME URL returns the cached failure without a
624
+ // network attempt. A changed query string is a new module-map key AND a
625
+ // new HTTP-cache key, so transient 404s (mid-update swap window, proxy
626
+ // hiccup) recover here without the full reload below.
627
+ const retryUrl = `${moduleUrl}${uiHashSuffix ? '&' : '?'}r=${Date.now().toString(36)}`;
628
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load, retrying with cache-bust…`, firstError);
629
+ plugin.module = await import(/* @vite-ignore */ retryUrl);
630
+ }
631
+ sessionStorage.removeItem(reloadKey);
632
+ } catch (e) {
633
+ // Classify the failure before deciding whether to reload. A reload only helps the
634
+ // genuinely *transient* cases — the plugin was updated and a chunk is mid-rename, or
635
+ // the file briefly 404s during the two-rename swap — where a fresh fetch resolves it.
636
+ //
637
+ // Version skew (see isVersionSkewError above): reloading punishes every fresh tab
638
+ // with a forced refresh loop, so we skip the plugin immediately with a warn and NO
639
+ // reload.
640
+ if (isVersionSkewError(e)) {
641
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load and looks like a version mismatch (the plugin may be built for an incompatible svelte/SDK version); skipping without reload.`, e);
642
+ sessionStorage.removeItem(reloadKey);
643
+ plugins.update((p) => {
644
+ delete p[pluginId];
645
+ return p;
646
+ });
647
+ return;
648
+ }
649
+
650
+ // Transient case (chunk-missing / mid-rename): reload once to resync — but only once
651
+ // per uiHash, since a permanent 404 would otherwise cause an infinite F5 loop.
652
+ const alreadyReloaded = sessionStorage.getItem(reloadKey) === '1';
653
+ if (!alreadyReloaded) {
654
+ sessionStorage.setItem(reloadKey, '1');
655
+ console.warn(`[Plugin Manager] '${pluginId}' client module failed to load, reloading once…`, e);
656
+ location.reload();
657
+ throw e;
658
+ }
659
+ // Second failure for the same uiHash: stop the loop. Drop the plugin from the store
660
+ // so the UI can render the rest of the page without it.
661
+ console.error(`[Plugin Manager] '${pluginId}' client module is permanently broken (uiHash=${plugin.uiHash}); skipping. The on-disk plugin files are likely corrupt — clear the panel-ui 'plugins/${pluginId}' folder on the server.`, e);
662
+ plugins.update((p) => {
663
+ delete p[pluginId];
664
+ return p;
665
+ });
666
+ }
667
+ } else {
668
+ const pluginFolder = path.join(pluginsFolder, pluginId);
669
+ const pluginManifest = plugin;
670
+ const pluginHash = pluginManifest.uiHash || "no-hash";
671
+ const cacheKey = `${pluginId}-${pluginHash}`;
672
+
673
+ if (moduleCache.has(cacheKey) && !siteInfo.developmentMode) {
674
+ plugin.module = moduleCache.get(cacheKey);
675
+ return;
676
+ }
677
+
678
+ // Cache-buster for Node's ESM module cache (keyed by resolved URL). In dev we use a
679
+ // timestamp so every SSR pass re-imports the freshly rebuilt module. In production we
680
+ // mirror the client branch and key on the plugin's uiHash: without this the ESM cache
681
+ // returns the STALE server module after a plugin update, producing an SSR/client
682
+ // hydration mismatch (client uses the new hashed module, server keeps the old one).
683
+ const importSuffix = siteInfo.developmentMode
684
+ ? `?${Date.now()}`
685
+ : (pluginHash !== "no-hash" ? `?v=${pluginHash}` : "");
686
+ const mainPath = path.join(pluginFolder, "server", "server.mjs") + importSuffix;
687
+
688
+ const __filename = url.fileURLToPath(import.meta.url);
689
+
690
+ const currentDir = path.dirname(__filename); // Directory of the current file
691
+ const targetFile = path.resolve(currentDir, process.cwd()); // Absolute path of the target file
692
+
693
+ const relativePath = path.relative(currentDir, targetFile);
694
+ const levels = relativePath.split(path.sep).length;
695
+
696
+ const upDirs = `..${path.sep}`.repeat(levels); // Repeating '../' based on the number of levels
697
+
698
+ let module;
699
+
700
+ try {
701
+ module = await import(/* @vite-ignore */ upDirs + mainPath);
702
+ } catch {
703
+ try {
704
+ module = await import(
705
+ /* @vite-ignore */ "file://" +
706
+ path.join(path.resolve(upDirs + mainPath, process.cwd(), mainPath))
707
+ );
708
+ } catch (e) {
709
+ error(`${pluginId} could not run! Error:`);
710
+ error(e);
711
+
712
+ plugins.update((p) => {
713
+ delete p[pluginId];
714
+ return p;
715
+ });
716
+
717
+ return;
718
+ }
719
+ }
720
+
721
+ plugin.module = module;
722
+ if (!siteInfo.developmentMode) {
723
+ // Evict this plugin's previous (different-uiHash) entries before caching the new one,
724
+ // so moduleCache stays bounded — without this it grew one stale entry per plugin
725
+ // update for the lifetime of the process, and old modules were never released.
726
+ const prefix = `${pluginId}-`;
727
+ for (const key of moduleCache.keys()) {
728
+ if (key !== cacheKey && key.startsWith(prefix)) {
729
+ moduleCache.delete(key);
730
+ }
731
+ }
732
+ moduleCache.set(cacheKey, module);
733
+ }
734
+ }
735
+ })
736
+ );
737
+
738
+ // Phase 2: Initialize plugins with dependency-aware batching (topological sort)
739
+ // Plugins at the same dependency level run in parallel; levels execute sequentially
740
+ const pluginDepGraph = buildPluginDependencyGraph(get(plugins));
741
+ const loadLevels = topologicalSortPlugins(pluginDepGraph);
742
+
743
+ for (const level of loadLevels) {
744
+ await Promise.all(
745
+ level.map(async (pluginId) => {
746
+ const plugin = get(plugins)[pluginId];
747
+ if (!plugin?.module?.default) return;
748
+
749
+ const PluginClass = plugin.module.default;
750
+
751
+ // Validate BEFORE instantiating. `PluginClass` is a constructor, so the old
752
+ // `PluginClass instanceof PanoPlugin` was always false and never rejected anything.
753
+ // A strict `prototype instanceof PanoPlugin` is wrong across bundles too: released
754
+ // plugins bundle their OWN copy of the SDK, so their PanoPlugin base class is a
755
+ // different identity than the host's. Accept the cross-bundle duck-type marker
756
+ // (`static isPanoPlugin`, inherited by subclasses), and skip the offending plugin
757
+ // instead of throwing — one bad plugin must not kill the whole load level.
758
+ const isValidPluginClass =
759
+ typeof PluginClass === "function" &&
760
+ (PluginClass === PanoPlugin ||
761
+ PluginClass.prototype instanceof PanoPlugin ||
762
+ PluginClass.isPanoPlugin === true);
763
+
764
+ if (!isValidPluginClass) {
765
+ error(`Plugin '${pluginId}' does not extend PanoPlugin; skipping.`);
766
+ plugins.update((p) => {
767
+ delete p[pluginId];
768
+ return p;
769
+ });
770
+ return;
771
+ }
772
+
773
+ const instance = new PluginClass({ pluginId });
774
+
775
+ instance.pano = browser ? panoApiClient : panoApiServer;
776
+
777
+ if (browser) {
778
+ livePluginInstances.set(pluginId, instance);
779
+ }
780
+
781
+ try {
782
+ await instance.onLoad();
783
+ } catch (e) {
784
+ if (dev) console.error(`[PluginManager] Failed to load plugin ${pluginId}:`, e);
785
+ }
786
+ })
787
+ );
788
+ }
789
+ }