@panomc/plugin-kit 0.0.0-stage → 1.0.0-dev.62

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 (89) hide show
  1. package/assets/pano-bootstrap.css +17903 -0
  2. package/bin/__tests__/new/e2e.test.js +111 -0
  3. package/bin/__tests__/new/helpers.js +76 -0
  4. package/bin/__tests__/new/new.test.js +472 -0
  5. package/bin/new.js +530 -0
  6. package/bin/pano-plugin.js +162 -0
  7. package/bin/templates/plugin/README.md +30 -0
  8. package/bin/templates/plugin/_gitignore +15 -0
  9. package/bin/templates/plugin/build.gradle.kts +389 -0
  10. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.jar +0 -0
  11. package/bin/templates/plugin/gradle/wrapper/gradle-wrapper.properties +7 -0
  12. package/bin/templates/plugin/gradle.properties +55 -0
  13. package/bin/templates/plugin/gradlew +249 -0
  14. package/bin/templates/plugin/gradlew.bat +92 -0
  15. package/bin/templates/plugin/package.json.tpl +14 -0
  16. package/bin/templates/plugin/rollup.config.js +2 -0
  17. package/bin/templates/plugin/settings.gradle.kts +5 -0
  18. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/__CLASS__Plugin.kt +50 -0
  19. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/frontend/ExampleFallbackPage.kt +28 -0
  20. package/bin/templates/plugin/src/main/kotlin/__PKGPATH__/routes/GetHelloAPI.kt +19 -0
  21. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/LicenseGuard.kt +30 -0
  22. package/bin/templates/plugin/src/main/kotlin/com/panomc/plugins/license/PluginLicenseClient.kt +144 -0
  23. package/bin/templates/plugin/src/main/resources/config.conf +1 -0
  24. package/bin/templates/plugin/src/main/resources/frontend-targets.json +1 -0
  25. package/bin/templates/plugin/src/main/resources/locales/en-US.json +3 -0
  26. package/bin/templates/plugin/src/main/resources/logo.png +0 -0
  27. package/bin/templates/plugin/src/theme/views/HelloPage.svelte +26 -0
  28. package/bin/ui.js +96 -0
  29. package/package.json +48 -4
  30. package/src/config.js +191 -0
  31. package/src/controller/__tests__/controller.test.js +647 -0
  32. package/src/controller/index.js +604 -0
  33. package/src/dev.js +208 -0
  34. package/src/index.js +22 -0
  35. package/src/rollup/__tests__/controllers/controllers.test.js +418 -0
  36. package/src/rollup/__tests__/controllers/fixture.js +143 -0
  37. package/src/rollup/__tests__/controllers/golden/controllers.json +34 -0
  38. package/src/rollup/__tests__/controllers/golden/controllers.types.js +69 -0
  39. package/src/rollup/__tests__/controllers/golden/pano-plugin.json +16 -0
  40. package/src/rollup/__tests__/controllers/golden/pano-plugin.lock.json +27 -0
  41. package/src/rollup/__tests__/controllers/golden/pano-plugin.with-views.json +54 -0
  42. package/src/rollup/__tests__/preset/preset.test.js +418 -0
  43. package/src/rollup/__tests__/rules/_build.js +39 -0
  44. package/src/rollup/__tests__/rules/_fixture.js +83 -0
  45. package/src/rollup/__tests__/rules/helpers.test.js +148 -0
  46. package/src/rollup/__tests__/rules/rules.test.js +259 -0
  47. package/src/rollup/__tests__/rules/stamp.test.js +113 -0
  48. package/src/rollup/__tests__/samples/samples.test.js +481 -0
  49. package/src/rollup/__tests__/seams/config.test.js +78 -0
  50. package/src/rollup/__tests__/seams/lock.test.js +124 -0
  51. package/src/rollup/__tests__/seams/sdk-seams.test.js +93 -0
  52. package/src/rollup/__tests__/seams/stubs.test.js +52 -0
  53. package/src/rollup/__tests__/views/helpers.js +82 -0
  54. package/src/rollup/__tests__/views/views.test.js +522 -0
  55. package/src/rollup/__tests__/widgets/helpers.js +117 -0
  56. package/src/rollup/__tests__/widgets/widgets.test.js +422 -0
  57. package/src/rollup/cli-build.js +90 -0
  58. package/src/rollup/cli-check.js +280 -0
  59. package/src/rollup/cli-classes.js +75 -0
  60. package/src/rollup/client-gen.js +67 -0
  61. package/src/rollup/controllers.js +434 -0
  62. package/src/rollup/entry.js +250 -0
  63. package/src/rollup/helpers.js +193 -0
  64. package/src/rollup/index.js +601 -0
  65. package/src/rollup/integrate.js +205 -0
  66. package/src/rollup/lock.js +230 -0
  67. package/src/rollup/meta.js +479 -0
  68. package/src/rollup/rules.js +950 -0
  69. package/src/rollup/samples.js +667 -0
  70. package/src/rollup/stamp.js +410 -0
  71. package/src/rollup/types.js +248 -0
  72. package/src/rollup/views.js +1205 -0
  73. package/src/rollup/widgets.js +1000 -0
  74. package/src/styles/__tests__/fallback/__snapshots__/build-fallback-css.test.js.snap +173 -0
  75. package/src/styles/__tests__/fallback/build-fallback-css.test.js +526 -0
  76. package/src/styles/__tests__/fallback/fixtures/base.css +247 -0
  77. package/src/styles/__tests__/fallback/plugins.test.js +301 -0
  78. package/src/styles/__tests__/lint/check-styles.test.js +423 -0
  79. package/src/styles/__tests__/lint/fixtures/ProductCard.golden.svelte +13 -0
  80. package/src/styles/__tests__/lint/fixtures/ProductCard.in.svelte +13 -0
  81. package/src/styles/__tests__/lint/semantic-classes.test.js +364 -0
  82. package/src/styles/bootstrap-classes.js +155 -0
  83. package/src/styles/check-styles.js +626 -0
  84. package/src/styles/fallback-css.js +1182 -0
  85. package/src/styles/plugin-css.js +237 -0
  86. package/src/styles/scan.js +206 -0
  87. package/src/styles/semantic-classes.js +436 -0
  88. package/src/styles/tokens.map.js +53 -0
  89. package/README.md +0 -3
@@ -0,0 +1,604 @@
1
+ // Controller core of @panomc/plugin-kit (doc 02 section 1).
2
+ //
3
+ // This file has NO module imports on purpose: the build copies it verbatim into the plugin's
4
+ // self-contained controllers/controllers.mjs, and it must run in any page, Worker or runtime.
5
+ // It must also stay free of framework code. Everything here is plain JavaScript over the Svelte
6
+ // store contract (get + subscribe), so a Svelte `$cart` works with no wrapper.
7
+
8
+ /**
9
+ * Header that carries the CSRF token on every mutation. This is a DUPLICATE of CSRF_HEADER in
10
+ * packages/sdk/core/js/variables.js (this file imports nothing); a kit test asserts they are equal.
11
+ */
12
+ export const CSRF_HEADER_NAME = 'X-CSRF-Token';
13
+
14
+ /** `/plugins/<id>/...` or `/api/plugins/<id>/...`, but not core's `/plugins/<id>/_/...` (decision 81). */
15
+ const PLUGIN_OWN_PATH = /^\/(?:api\/)?plugins\/[^/?#]+\/(?!_(?:[/?#]|$))[^?#]/;
16
+
17
+ /**
18
+ * @typedef {Object} ControllerHost
19
+ * @property {string} baseUrl
20
+ * @property {boolean} browser
21
+ * @property {(r:{method?:string, path:string, query?:object, body?:any, headers?:object, blob?:boolean}) => Promise<any>} request
22
+ * Parsed body in doc 04's shape (non-2xx = { error: { code, ... } }). `path` is what follows "/api/v1".
23
+ * A network failure resolves { error: { code: 'NETWORK_ERROR' } }; request never rejects.
24
+ * @property {() => {user:(object|null), csrfToken:(string|null)}} session
25
+ * @property {() => (string|undefined)} locale
26
+ * @property {(fn:(s:any)=>void) => (() => void)} onSession first bind, login, logout; a no-op on the server
27
+ * @property {(key:string, values?:object) => string} t full key: "plugins.pano-plugin-market.x"
28
+ * @property {(key:string, o?:{variant?:'success'|'danger'|'warning', values?:object}) => void} toast
29
+ * @property {(kind:'local'|'session') => (Storage|null)} storage
30
+ * @property {() => number} now
31
+ * @property {(url:string, o?:{replace?:boolean}) => void} navigate
32
+ * @property {(name:string) => boolean} feature
33
+ * @property {(returnTo?:string) => string} loginUrl
34
+ * @property {(returnTo?:string) => string} registerUrl
35
+ */
36
+
37
+ /**
38
+ * @template S
39
+ * @typedef {Object} Store
40
+ * @property {() => S} get
41
+ * @property {(run:(s:S)=>void) => (() => void)} subscribe calls run synchronously once, then on every change
42
+ */
43
+
44
+ /**
45
+ * @template S
46
+ * @typedef {Store<S> & {set:(s:S)=>void, update:(f:(s:S)=>S)=>void}} State
47
+ */
48
+
49
+ /**
50
+ * @template S, A
51
+ * @typedef {Object} Ctx
52
+ * @property {ControllerHost} host
53
+ * @property {object} params
54
+ * @property {() => S} get
55
+ * @property {(s:S) => void} set
56
+ * @property {(f:(s:S)=>S) => void} update
57
+ * @property {(name:string) => Controller<any, any>} use a sibling controller of the same plugin, same host
58
+ */
59
+
60
+ /**
61
+ * What a theme, a web component or plain JS holds. `name` is "market/cart" (namespace + "/" + spec.name).
62
+ * `get()` is a snapshot, replaced on change and never mutated.
63
+ * @template S, A
64
+ * @typedef {Object} Controller
65
+ * @property {string} name
66
+ * @property {number} version
67
+ * @property {() => S} get
68
+ * @property {(run:(s:S)=>void) => (() => void)} subscribe
69
+ * @property {A} actions
70
+ * @property {() => void} destroy
71
+ */
72
+
73
+ /**
74
+ * @template S, A
75
+ * @typedef {Object} ControllerSpec
76
+ * @property {string} name camelCase, unique in the plugin: "cart"
77
+ * @property {number} version contract version, integer >= 1
78
+ * @property {'app'|'instance'} [scope] 'app' (default) one per page; 'instance' one per use()
79
+ * @property {boolean} [eager] app scope: created and started right after register() in the browser
80
+ * @property {(c:{host:ControllerHost, params:object}) => S} [state] initial state holding EVERY public key; accepts params {}
81
+ * @property {(c:Ctx<S,A>) => A} [actions] plain functions; default () => ({})
82
+ * @property {(c:Ctx<S,A> & {actions:A}) => (void|(() => void))} [start] browser only. Runs on the first subscriber
83
+ * (eager: at creation); the returned function runs after the last subscriber leaves (eager: on destroy)
84
+ * @property {(c:{host:ControllerHost, params:object}) => Promise<object>} [load] SSR-safe page loader, no instance state
85
+ */
86
+
87
+ /**
88
+ * What defineController returns.
89
+ * @template S, A
90
+ * @typedef {Object} ControllerDefinition
91
+ * @property {string} name
92
+ * @property {number} version
93
+ * @property {'app'|'instance'} scope
94
+ * @property {boolean} eager
95
+ * @property {ControllerSpec<S,A>} spec
96
+ * @property {((c:{host:ControllerHost, params:object}) => Promise<object>)|undefined} load
97
+ * @property {(host:ControllerHost, params?:object, initial?:object, opts?:{namespace?:string, use?:(name:string)=>Controller<any,any>}) => Controller<S,A>} create
98
+ * `initial` is a patch merged over the initial state. opts.namespace gives the controller its full name,
99
+ * opts.use resolves siblings for ctx.use (the registry passes both).
100
+ */
101
+
102
+ const NOOP = () => {};
103
+ const NAME_RE = /^[a-z][A-Za-z0-9]*$/;
104
+
105
+ /** Makes an unsubscribe function that only does its work once. */
106
+ function once(fn) {
107
+ let done = false;
108
+ return () => {
109
+ if (done) return;
110
+ done = true;
111
+ fn();
112
+ };
113
+ }
114
+
115
+ /**
116
+ * A tiny store. `set` notifies only when `!Object.is(prev, next)`, synchronously and in order (a set
117
+ * made inside a subscriber is queued behind the notification that is running).
118
+ * @template S
119
+ * @param {S} initial
120
+ * @returns {State<S>}
121
+ */
122
+ export function createState(initial) {
123
+ let value = initial;
124
+ const subscribers = new Set();
125
+ const pending = [];
126
+ let flushing = false;
127
+
128
+ function flush() {
129
+ flushing = true;
130
+ try {
131
+ while (pending.length) {
132
+ const next = pending.shift();
133
+ for (const run of [...subscribers]) {
134
+ if (subscribers.has(run)) run(next);
135
+ }
136
+ }
137
+ } finally {
138
+ pending.length = 0;
139
+ flushing = false;
140
+ }
141
+ }
142
+
143
+ function set(next) {
144
+ if (Object.is(value, next)) return;
145
+ value = next;
146
+ pending.push(next);
147
+ if (!flushing) flush();
148
+ }
149
+
150
+ return {
151
+ get: () => value,
152
+ set,
153
+ update: (f) => set(f(value)),
154
+ subscribe(run) {
155
+ // A fresh wrapper per subscription, so the same function may subscribe twice.
156
+ const entry = (s) => run(s);
157
+ subscribers.add(entry);
158
+ run(value);
159
+ return once(() => {
160
+ subscribers.delete(entry);
161
+ });
162
+ },
163
+ };
164
+ }
165
+
166
+ /**
167
+ * A store computed from one store (fn receives its value) or an array of stores (fn receives an array of
168
+ * values). Subscribes to the sources on the first subscriber and lets go after the last. Without
169
+ * subscribers `get()` recomputes only when a source value changed.
170
+ * @param {Store<any> | Store<any>[]} sources
171
+ * @param {(v:any) => any} fn
172
+ * @returns {Store<any>}
173
+ */
174
+ export function derive(sources, fn) {
175
+ const multi = Array.isArray(sources);
176
+ const list = multi ? sources : [sources];
177
+ const inner = createState(undefined);
178
+ let subscribers = 0;
179
+ let unsubs = [];
180
+ let lastInputs = null;
181
+ let lastOutput;
182
+
183
+ function compute() {
184
+ const inputs = list.map((s) => s.get());
185
+ if (lastInputs && inputs.every((v, i) => Object.is(v, lastInputs[i]))) return lastOutput;
186
+ lastInputs = inputs;
187
+ lastOutput = fn(multi ? inputs : inputs[0]);
188
+ return lastOutput;
189
+ }
190
+
191
+ return {
192
+ get: () => (subscribers > 0 ? inner.get() : compute()),
193
+ subscribe(run) {
194
+ if (subscribers === 0) {
195
+ let initializing = true;
196
+ unsubs = list.map((s) =>
197
+ s.subscribe(() => {
198
+ if (!initializing) inner.set(compute());
199
+ }),
200
+ );
201
+ initializing = false;
202
+ inner.set(compute());
203
+ }
204
+ subscribers++;
205
+ const off = inner.subscribe(run);
206
+ return once(() => {
207
+ off();
208
+ subscribers--;
209
+ if (subscribers === 0) {
210
+ for (const u of unsubs) u();
211
+ unsubs = [];
212
+ }
213
+ });
214
+ },
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Declares a controller. Nothing is created until `create(host, params, initial, opts)` is called.
220
+ * @template S, A
221
+ * @param {ControllerSpec<S,A>} spec
222
+ * @returns {ControllerDefinition<S,A>}
223
+ */
224
+ export function defineController(spec) {
225
+ if (!spec || typeof spec !== 'object') throw new TypeError('defineController: a spec object is required');
226
+ if (typeof spec.name !== 'string' || !NAME_RE.test(spec.name)) {
227
+ throw new TypeError(`defineController: name must be camelCase, got ${JSON.stringify(spec.name)}`);
228
+ }
229
+ if (!Number.isInteger(spec.version) || spec.version < 1) {
230
+ throw new TypeError(`defineController(${spec.name}): version must be an integer >= 1`);
231
+ }
232
+ const scope = spec.scope ?? 'app';
233
+ if (scope !== 'app' && scope !== 'instance') {
234
+ throw new TypeError(`defineController(${spec.name}): scope must be 'app' or 'instance'`);
235
+ }
236
+ for (const key of ['state', 'actions', 'start', 'load']) {
237
+ if (spec[key] != null && typeof spec[key] !== 'function') {
238
+ throw new TypeError(`defineController(${spec.name}): ${key} must be a function`);
239
+ }
240
+ }
241
+
242
+ const definition = {
243
+ name: spec.name,
244
+ version: spec.version,
245
+ scope,
246
+ eager: spec.eager === true,
247
+ spec,
248
+ create(host, params, initial, opts) {
249
+ return createController(definition, host, params, initial, opts);
250
+ },
251
+ };
252
+ definition.load = spec.load || undefined;
253
+ return definition;
254
+ }
255
+
256
+ function createController(def, host, params, initial, opts) {
257
+ const spec = def.spec;
258
+ const theHost = host || nullHost;
259
+ const theParams = params || {};
260
+ const fullName = opts && opts.namespace ? `${opts.namespace}/${def.name}` : def.name;
261
+
262
+ let first = spec.state ? spec.state({ host: theHost, params: theParams }) : {};
263
+ if (initial && typeof initial === 'object') first = { ...first, ...initial };
264
+ const store = createState(first);
265
+
266
+ const ctx = {
267
+ host: theHost,
268
+ params: theParams,
269
+ get: store.get,
270
+ set: store.set,
271
+ update: store.update,
272
+ use(name) {
273
+ if (opts && typeof opts.use === 'function') return opts.use(name);
274
+ throw new Error(`ctx.use('${name}'): this controller was created outside a registry`);
275
+ },
276
+ };
277
+
278
+ const actions = spec.actions ? spec.actions(ctx) || {} : {};
279
+ const startCtx = { ...ctx, actions };
280
+
281
+ let destroyed = false;
282
+ let running = false;
283
+ let cleanup = null;
284
+ let count = 0;
285
+ const live = new Set();
286
+ const canStart = () => !destroyed && !!spec.start && theHost.browser === true;
287
+
288
+ function startNow() {
289
+ if (running || !canStart()) return;
290
+ running = true;
291
+ try {
292
+ const stop = spec.start(startCtx);
293
+ cleanup = typeof stop === 'function' ? stop : null;
294
+ } catch (e) {
295
+ console.error(`[pano] controller '${fullName}' start failed`, e);
296
+ }
297
+ }
298
+
299
+ function stopNow() {
300
+ if (!running) return;
301
+ running = false;
302
+ const stop = cleanup;
303
+ cleanup = null;
304
+ if (stop) {
305
+ try {
306
+ stop();
307
+ } catch (e) {
308
+ console.error(`[pano] controller '${fullName}' stop failed`, e);
309
+ }
310
+ }
311
+ }
312
+
313
+ const controller = {
314
+ name: fullName,
315
+ version: def.version,
316
+ get: store.get,
317
+ actions,
318
+ subscribe(run) {
319
+ // Start BEFORE the subscriber joins: whatever start sets synchronously is already in the first value.
320
+ if (count === 0 && !def.eager) startNow();
321
+ count++;
322
+ const off = store.subscribe(run);
323
+ const done = once(() => {
324
+ off();
325
+ live.delete(done);
326
+ count--;
327
+ if (count === 0 && !def.eager) stopNow();
328
+ });
329
+ live.add(done);
330
+ return done;
331
+ },
332
+ destroy() {
333
+ if (destroyed) return;
334
+ destroyed = true;
335
+ for (const off of [...live]) off();
336
+ stopNow();
337
+ },
338
+ };
339
+
340
+ if (def.eager) startNow();
341
+ return controller;
342
+ }
343
+
344
+ // ---------------------------------------------------------------------------------------------
345
+ // Hosts
346
+ // ---------------------------------------------------------------------------------------------
347
+
348
+ const GUEST_SESSION = Object.freeze({ user: null, csrfToken: null });
349
+
350
+ /** Guest session, `request` resolves NULL_HOST, everything else is a safe no-op. */
351
+ export const nullHost = Object.freeze({
352
+ baseUrl: '',
353
+ browser: false,
354
+ request: () => Promise.resolve({ error: { code: 'NULL_HOST' } }),
355
+ session: () => GUEST_SESSION,
356
+ locale: () => undefined,
357
+ onSession: () => NOOP,
358
+ t: (key) => key,
359
+ toast: NOOP,
360
+ storage: () => null,
361
+ now: () => Date.now(),
362
+ navigate: NOOP,
363
+ feature: () => false,
364
+ loginUrl: () => '/login',
365
+ registerUrl: () => '/register',
366
+ });
367
+
368
+ function interpolate(text, values) {
369
+ if (!values) return text;
370
+ return text.replace(/\{\s*([\w.-]+)\s*\}/g, (m, k) => (k in values && values[k] != null ? String(values[k]) : m));
371
+ }
372
+
373
+ function withReturn(base, returnTo) {
374
+ return returnTo ? `${base}?redirect=${encodeURIComponent(returnTo)}` : base;
375
+ }
376
+
377
+ function buildQueryString(query) {
378
+ if (!query || typeof query !== 'object') return '';
379
+ const parts = new URLSearchParams();
380
+ for (const [key, value] of Object.entries(query)) {
381
+ if (value === undefined || value === null) continue;
382
+ if (Array.isArray(value)) {
383
+ for (const v of value) if (v !== undefined && v !== null) parts.append(key, String(v));
384
+ } else {
385
+ parts.append(key, String(value));
386
+ }
387
+ }
388
+ const text = parts.toString();
389
+ return text ? `?${text}` : '';
390
+ }
391
+
392
+ function isRawBody(body) {
393
+ return (
394
+ typeof body === 'string' ||
395
+ (typeof FormData !== 'undefined' && body instanceof FormData) ||
396
+ (typeof Blob !== 'undefined' && body instanceof Blob) ||
397
+ (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) ||
398
+ (typeof ArrayBuffer !== 'undefined' && (body instanceof ArrayBuffer || ArrayBuffer.isView(body)))
399
+ );
400
+ }
401
+
402
+ const networkError = () => ({ error: { code: 'NETWORK_ERROR' } });
403
+
404
+ /**
405
+ * A host over `fetch`, for web components, the starter and non-Svelte front-ends.
406
+ * `baseUrl` is what precedes "/api/v1" (Pano's origin, or a proxy prefix such as "/pano"); request paths
407
+ * are the part after "/api/v1". `getToken` sends `Authorization: Bearer`, else cookies (`credentials: 'include'`).
408
+ * `locale` may be a string or a function; `messages` is a flat map of full key to text; `features` is an
409
+ * array, a Set, an object map or a function; `storage` is a function (kind) or `{ local, session }`.
410
+ * Extras beyond doc 02: `browser`, `now`, `getSession` (returns { user }), `onSession` (subscribe function).
411
+ * `onToast(key, { variant, values, message })` receives the translated text as `message`.
412
+ * @param {{baseUrl:string, fetch?:Function, getToken?:()=>(string|null|undefined), getCsrf?:()=>(string|null|undefined),
413
+ * locale?:(string|(()=>string|undefined)), messages?:Record<string,string>,
414
+ * features?:(string[]|Set<string>|Record<string,boolean>|((name:string)=>boolean)),
415
+ * loginUrl?:(returnTo?:string)=>string, registerUrl?:(returnTo?:string)=>string,
416
+ * onToast?:(key:string, o:object)=>void, onNavigate?:(url:string, o?:{replace?:boolean})=>void,
417
+ * storage?:(((kind:'local'|'session')=>Storage|null)|{local?:Storage, session?:Storage}),
418
+ * browser?:boolean, now?:()=>number, getSession?:()=>({user?:object|null}|null|undefined),
419
+ * onSession?:(fn:(s:any)=>void)=>(()=>void)}} options
420
+ * @returns {ControllerHost}
421
+ */
422
+ export function createFetchHost(options = {}) {
423
+ const o = options || {};
424
+ const baseUrl = String(o.baseUrl ?? '').replace(/\/+$/, '');
425
+ const browser = typeof o.browser === 'boolean' ? o.browser : typeof window !== 'undefined';
426
+ const doFetch = (...args) => (o.fetch || globalThis.fetch)(...args);
427
+
428
+ const t = (key, values) => {
429
+ const text = o.messages && typeof o.messages[key] === 'string' ? o.messages[key] : key;
430
+ return interpolate(text, values);
431
+ };
432
+
433
+ async function request(r) {
434
+ try {
435
+ const { method = 'GET', path = '', query, body, headers, blob } = r || {};
436
+ const verb = String(method).toUpperCase();
437
+ const rooted = path.startsWith('/') || path === '' ? path : `/${path}`;
438
+ // A plugin's own endpoints are unversioned (decision 81): `/plugins/<id>/...` goes to `/api/plugins/<id>/...`.
439
+ const root = PLUGIN_OWN_PATH.test(rooted) ? '/api' : '/api/v1';
440
+ const url = `${baseUrl}${root}${rooted.replace(/^\/api(?=\/plugins\/)/, '')}${buildQueryString(query)}`;
441
+
442
+ const sent = { Accept: 'application/json' };
443
+ const init = { method: verb, headers: sent };
444
+ const token = o.getToken ? o.getToken() : null;
445
+ if (token) sent.Authorization = `Bearer ${token}`;
446
+ else init.credentials = 'include';
447
+
448
+ const csrf = o.getCsrf ? o.getCsrf() : null;
449
+ if (csrf && verb !== 'GET' && verb !== 'HEAD') sent[CSRF_HEADER_NAME] = csrf;
450
+
451
+ if (body !== undefined && body !== null && verb !== 'GET' && verb !== 'HEAD') {
452
+ if (isRawBody(body)) {
453
+ init.body = body;
454
+ } else {
455
+ sent['Content-Type'] = 'application/json';
456
+ init.body = JSON.stringify(body);
457
+ }
458
+ }
459
+ if (headers) Object.assign(sent, headers);
460
+
461
+ const res = await doFetch(url, init);
462
+
463
+ if (blob && res.ok) return await res.blob();
464
+
465
+ const text = await res.text();
466
+ let parsed;
467
+ let parseFailed = false;
468
+ if (text) {
469
+ try {
470
+ parsed = JSON.parse(text);
471
+ } catch (e) {
472
+ parseFailed = true;
473
+ }
474
+ }
475
+
476
+ if (res.ok) {
477
+ if (!text) return {};
478
+ return parseFailed ? { error: { code: 'INVALID_RESPONSE' } } : parsed;
479
+ }
480
+ if (!parseFailed && parsed && typeof parsed === 'object' && parsed.error) return parsed;
481
+ return { error: { code: 'UNKNOWN_ERROR', details: { status: res.status } } };
482
+ } catch (e) {
483
+ return networkError();
484
+ }
485
+ }
486
+
487
+ const hasFeature = (name) => {
488
+ const f = o.features;
489
+ if (!f) return false;
490
+ if (typeof f === 'function') return !!f(name);
491
+ if (Array.isArray(f)) return f.includes(name);
492
+ if (typeof f.has === 'function') return !!f.has(name);
493
+ return f[name] === true;
494
+ };
495
+
496
+ function storage(kind) {
497
+ try {
498
+ if (typeof o.storage === 'function') return o.storage(kind) || null;
499
+ if (o.storage && typeof o.storage === 'object') return o.storage[kind] || null;
500
+ if (!browser) return null;
501
+ return (kind === 'session' ? globalThis.sessionStorage : globalThis.localStorage) || null;
502
+ } catch (e) {
503
+ return null;
504
+ }
505
+ }
506
+
507
+ return {
508
+ baseUrl,
509
+ browser,
510
+ request,
511
+ session() {
512
+ let user = null;
513
+ try {
514
+ user = (o.getSession && o.getSession()?.user) || null;
515
+ } catch (e) {
516
+ user = null;
517
+ }
518
+ return { user, csrfToken: (o.getCsrf && o.getCsrf()) || null };
519
+ },
520
+ locale: () => (typeof o.locale === 'function' ? o.locale() : o.locale),
521
+ onSession: (fn) => (typeof o.onSession === 'function' ? o.onSession(fn) || NOOP : NOOP),
522
+ t,
523
+ toast(key, opts) {
524
+ if (!o.onToast) return;
525
+ const values = opts && opts.values;
526
+ o.onToast(key, { ...(opts || {}), message: t(key, values) });
527
+ },
528
+ storage,
529
+ now: () => (o.now ? o.now() : Date.now()),
530
+ navigate(url, opts) {
531
+ if (o.onNavigate) return o.onNavigate(url, opts);
532
+ if (!browser || typeof location === 'undefined') return;
533
+ if (opts && opts.replace) location.replace(url);
534
+ else location.assign(url);
535
+ },
536
+ feature: hasFeature,
537
+ loginUrl: (returnTo) => (o.loginUrl ? o.loginUrl(returnTo) : withReturn('/login', returnTo)),
538
+ registerUrl: (returnTo) => (o.registerUrl ? o.registerUrl(returnTo) : withReturn('/register', returnTo)),
539
+ };
540
+ }
541
+
542
+ // ---------------------------------------------------------------------------------------------
543
+ // Sample controller (view catalogue, doc 02 section 7)
544
+ // ---------------------------------------------------------------------------------------------
545
+
546
+ /**
547
+ * A controller with a FIXED state: the definition's initial state (built on `nullHost`, empty params)
548
+ * with `patch` merged over it. Its actions have the names of the real ones but only record
549
+ * `{ name, args }` into `controller.calls` and resolve `{ ok: true }`; nothing else runs and nothing
550
+ * touches the registry cache. `start` never runs.
551
+ * @param {ControllerDefinition<any,any>} def
552
+ * @param {object} [patch]
553
+ * @param {{namespace?:string, use?:(name:string)=>Controller<any,any>, onCall?:(call:{name:string,args:any[]})=>void}} [opts]
554
+ * @returns {Controller<any,any> & {calls:{name:string,args:any[]}[]}}
555
+ */
556
+ export function createSampleController(def, patch, opts) {
557
+ const spec = def.spec || {};
558
+ const o = opts || {};
559
+ let first = spec.state ? spec.state({ host: nullHost, params: {} }) : {};
560
+ if (patch && typeof patch === 'object') first = { ...first, ...patch };
561
+ const store = createState(first);
562
+ const calls = [];
563
+
564
+ // Learn the action names from the real factory on a sandbox ctx whose writes go nowhere.
565
+ let names = [];
566
+ if (spec.actions) {
567
+ try {
568
+ const real = spec.actions({
569
+ host: nullHost,
570
+ params: {},
571
+ get: store.get,
572
+ set: NOOP,
573
+ update: NOOP,
574
+ use: (name) => {
575
+ if (typeof o.use === 'function') return o.use(name);
576
+ return { name, version: 0, get: () => ({}), subscribe: (run) => (run({}), NOOP), actions: {}, destroy: NOOP };
577
+ },
578
+ });
579
+ names = Object.keys(real || {});
580
+ } catch (e) {
581
+ names = [];
582
+ }
583
+ }
584
+
585
+ const actions = {};
586
+ for (const name of names) {
587
+ actions[name] = (...args) => {
588
+ const call = { name, args };
589
+ calls.push(call);
590
+ if (o.onCall) o.onCall(call);
591
+ return Promise.resolve({ ok: true });
592
+ };
593
+ }
594
+
595
+ return {
596
+ name: o.namespace ? `${o.namespace}/${def.name}` : def.name,
597
+ version: def.version,
598
+ get: store.get,
599
+ subscribe: store.subscribe,
600
+ actions,
601
+ calls,
602
+ destroy: NOOP,
603
+ };
604
+ }