noofpi 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -2
  3. package/bin/noofpi.mjs +2 -0
  4. package/client.d.ts +79 -0
  5. package/dist/build-77DKK3YK.js +48 -0
  6. package/dist/chunk-2XCZWFIQ.js +253 -0
  7. package/dist/chunk-6OWKWAIW.js +68 -0
  8. package/dist/chunk-ELXCFUA4.js +97 -0
  9. package/dist/chunk-EZPJF4D4.js +314 -0
  10. package/dist/chunk-FIJJ3EGL.js +353 -0
  11. package/dist/chunk-G35DW4NA.js +129 -0
  12. package/dist/chunk-KAV3UNMO.js +996 -0
  13. package/dist/chunk-KGZP2RCF.js +51 -0
  14. package/dist/chunk-MTWSTW7V.js +44 -0
  15. package/dist/chunk-MTXQR32N.js +8 -0
  16. package/dist/chunk-NALDZ3PS.js +90 -0
  17. package/dist/chunk-WX2V6EYH.js +102 -0
  18. package/dist/chunk-WXEYXDO6.js +280 -0
  19. package/dist/chunk-X34Y6ESE.js +810 -0
  20. package/dist/chunk-Y3NBZ6DW.js +55 -0
  21. package/dist/chunk-YZAZ7IWK.js +27 -0
  22. package/dist/cli.js +93 -0
  23. package/dist/dev-ZJ732ORK.js +122 -0
  24. package/dist/devtools-KTDSD5PR.js +564 -0
  25. package/dist/images-BNwTAi50.d.ts +36 -0
  26. package/dist/index.d.ts +115 -0
  27. package/dist/index.js +15 -0
  28. package/dist/route-rules-COilNsVT.d.ts +127 -0
  29. package/dist/runtime/default-app.js +15 -0
  30. package/dist/runtime/entry-client.js +70 -0
  31. package/dist/runtime/entry-server.js +107 -0
  32. package/dist/runtime/index.d.ts +523 -0
  33. package/dist/runtime/index.js +224 -0
  34. package/dist/runtime/routes.js +14 -0
  35. package/dist/server/bun.js +47 -0
  36. package/dist/server/index.d.ts +109 -0
  37. package/dist/server/index.js +48 -0
  38. package/dist/server/node.js +15 -0
  39. package/dist/start-I2LQWV7B.js +61 -0
  40. package/dist/validation-ClXd_DAW.d.ts +159 -0
  41. package/package.json +101 -4
@@ -0,0 +1,810 @@
1
+ import {
2
+ createMiddlewareGuard,
3
+ createMiddlewareRegistry
4
+ } from "./chunk-6OWKWAIW.js";
5
+ import {
6
+ LOCALE_COOKIE,
7
+ matchLocale,
8
+ parseAcceptLanguage,
9
+ pickLocale,
10
+ textDirection,
11
+ translate
12
+ } from "./chunk-ELXCFUA4.js";
13
+ import {
14
+ createCookieJar,
15
+ createError,
16
+ isNoofpiError,
17
+ mergeCookieOptions,
18
+ readPayload,
19
+ stringCodec,
20
+ toErrorData
21
+ } from "./chunk-EZPJF4D4.js";
22
+ import {
23
+ HEAD_ATTRS_ATTR,
24
+ HEAD_TAG_ATTR,
25
+ resolveHead
26
+ } from "./chunk-G35DW4NA.js";
27
+ import {
28
+ FETCH_MODES,
29
+ isServerRendered,
30
+ resolveFetchMode,
31
+ usesFetchMode
32
+ } from "./chunk-FIJJ3EGL.js";
33
+
34
+ // src/runtime/async-data.ts
35
+ import {
36
+ inject,
37
+ onServerPrefetch,
38
+ ref
39
+ } from "vue";
40
+ var PAYLOAD_KEY = /* @__PURE__ */ Symbol("noofpi:payload");
41
+ function toError(error, server = false) {
42
+ const { message, status } = error ?? {};
43
+ return {
44
+ message: server && !isNoofpiError(error) ? "Internal Server Error" : typeof message === "string" ? message : String(error),
45
+ ...typeof status === "number" ? { status } : {}
46
+ };
47
+ }
48
+ function useAsyncData(key, handler, options = {}) {
49
+ const payload = inject(PAYLOAD_KEY, null);
50
+ if (!payload)
51
+ throw new Error("[noofpi] useAsyncData() must be called inside setup()");
52
+ const hydrated = !payload.server && (key in payload.data || key in payload.errors);
53
+ const data = ref(hydrated ? payload.data[key] : void 0);
54
+ const error = ref(hydrated ? payload.errors[key] : void 0);
55
+ const pending = ref(!hydrated);
56
+ const refresh = async () => {
57
+ pending.value = true;
58
+ error.value = void 0;
59
+ try {
60
+ data.value = await handler();
61
+ } catch (e) {
62
+ error.value = toError(e, payload.server);
63
+ } finally {
64
+ pending.value = false;
65
+ }
66
+ };
67
+ if (payload.server) {
68
+ if (options.server !== false) {
69
+ onServerPrefetch(async () => {
70
+ await refresh();
71
+ if (error.value) payload.errors[key] = error.value;
72
+ else payload.data[key] = data.value === void 0 ? null : data.value;
73
+ });
74
+ }
75
+ } else if (!hydrated) {
76
+ void refresh();
77
+ }
78
+ return { data, error, pending, refresh };
79
+ }
80
+
81
+ // src/runtime/loader.ts
82
+ import {
83
+ computed,
84
+ inject as inject2,
85
+ ref as ref2,
86
+ shallowRef
87
+ } from "vue";
88
+ import {
89
+ useRoute
90
+ } from "vue-router";
91
+ function definePage(page) {
92
+ return page;
93
+ }
94
+ var LOADER_KEY = /* @__PURE__ */ Symbol("noofpi:loader");
95
+ var PREFETCH_TTL_MS = 3e4;
96
+ var loaderKey = (route) => "loader:" + route.fullPath.replace(/#.*$/, "");
97
+ function loaderOf(route) {
98
+ const loader = route.matched[route.matched.length - 1]?.meta.loader;
99
+ return typeof loader === "function" ? loader : void 0;
100
+ }
101
+ function installLoaders(router, options) {
102
+ const { payload, run } = options;
103
+ const state = {
104
+ current: shallowRef(),
105
+ pending: ref2(false),
106
+ async refresh() {
107
+ const route = router.currentRoute.value;
108
+ if (!loaderOf(route)) return;
109
+ state.pending.value = true;
110
+ try {
111
+ state.current.value = await execute(route);
112
+ } finally {
113
+ state.pending.value = false;
114
+ }
115
+ }
116
+ };
117
+ const results = /* @__PURE__ */ new Map();
118
+ const prefetched = /* @__PURE__ */ new Map();
119
+ async function execute(to) {
120
+ const key = loaderKey(to);
121
+ try {
122
+ const loader = loaderOf(to);
123
+ const data = await run(
124
+ to,
125
+ () => loader({ route: to, params: to.params, query: to.query })
126
+ );
127
+ return { key, data };
128
+ } catch (error) {
129
+ return { key, error: toError(error, payload.server) };
130
+ }
131
+ }
132
+ router.beforeResolve(async (to) => {
133
+ if (!loaderOf(to)) return;
134
+ const key = loaderKey(to);
135
+ if (state.current.value?.key === key) return;
136
+ let entry;
137
+ const cached = prefetched.get(key);
138
+ prefetched.delete(key);
139
+ if (!payload.server && key in payload.data) {
140
+ entry = { key, data: payload.data[key] };
141
+ } else if (!payload.server && key in payload.errors) {
142
+ entry = { key, error: payload.errors[key] };
143
+ } else if (cached && Date.now() - cached.at < PREFETCH_TTL_MS) {
144
+ entry = await cached.entry;
145
+ } else {
146
+ entry = await execute(to);
147
+ }
148
+ if (payload.server) {
149
+ if (entry.error) payload.errors[key] = entry.error;
150
+ else payload.data[key] = entry.data === void 0 ? null : entry.data;
151
+ }
152
+ results.set(key, entry);
153
+ });
154
+ router.afterEach((to, _from, failure) => {
155
+ if (failure) return;
156
+ const key = loaderKey(to);
157
+ const entry = results.get(key);
158
+ results.delete(key);
159
+ if (entry) state.current.value = entry;
160
+ else if (state.current.value?.key !== key) state.current.value = void 0;
161
+ });
162
+ router.onError(() => results.clear());
163
+ async function prefetch(href) {
164
+ const to = router.resolve(href);
165
+ const record = to.matched[to.matched.length - 1];
166
+ if (!record) return;
167
+ const key = loaderKey(to);
168
+ const known = prefetched.get(key);
169
+ if (known && Date.now() - known.at < PREFETCH_TTL_MS) return;
170
+ if (key === loaderKey(router.currentRoute.value)) return;
171
+ const component = record.components?.default;
172
+ if (typeof component === "function" && !("__vccOpts" in component))
173
+ await component();
174
+ if (!loaderOf(to)) return;
175
+ for (const [other, { at }] of prefetched)
176
+ if (Date.now() - at >= PREFETCH_TTL_MS) prefetched.delete(other);
177
+ const entry = execute(to);
178
+ prefetched.set(key, { at: Date.now(), entry });
179
+ await entry;
180
+ }
181
+ return { state, prefetch };
182
+ }
183
+ function useLoaderData(page) {
184
+ const state = inject2(LOADER_KEY, null);
185
+ if (!state)
186
+ throw new Error("[noofpi] useLoaderData() must be called inside setup()");
187
+ if (import.meta.env.DEV) {
188
+ const route = useRoute();
189
+ if (loaderOf(route) !== page.loader)
190
+ console.warn(
191
+ `[noofpi] useLoaderData() was called with a page whose loader does not belong to ${route.path}. Pass the \`page\` that this file exports from a plain <script> block.`
192
+ );
193
+ }
194
+ return {
195
+ data: computed(() => state.current.value?.data),
196
+ error: computed(() => state.current.value?.error),
197
+ pending: state.pending,
198
+ refresh: state.refresh
199
+ };
200
+ }
201
+
202
+ // src/runtime/inspector.ts
203
+ import { reactive } from "vue";
204
+ var MAX_REQUESTS = 100;
205
+ var createRequestLog = () => reactive({ list: [] });
206
+ function addEntries(log, entries) {
207
+ log.list = [...log.list, ...entries].slice(-MAX_REQUESTS);
208
+ }
209
+ var snapshotEntries = (log) => log.list.map((entry) => ({ ...entry }));
210
+ function recordFetch(base, log, info) {
211
+ return async (input, init) => {
212
+ addEntries(log, [
213
+ {
214
+ ...info,
215
+ method: (init?.method ?? "GET").toUpperCase(),
216
+ url: input
217
+ }
218
+ ]);
219
+ const entry = log.list.at(-1);
220
+ const start = performance.now();
221
+ try {
222
+ const response = await base(input, init);
223
+ entry.status = response.status;
224
+ return response;
225
+ } catch (failure) {
226
+ entry.error = failure instanceof Error ? failure.message : String(failure);
227
+ throw failure;
228
+ } finally {
229
+ entry.ms = Math.round(performance.now() - start);
230
+ }
231
+ };
232
+ }
233
+
234
+ // src/runtime/doofpi-client.ts
235
+ import { createClient } from "doofpi";
236
+ import { inject as inject3 } from "vue";
237
+ import { routeLocationKey } from "vue-router";
238
+ var PROXY_PREFIX = "/_noofpi/proxy";
239
+ var DOOFPI_KEY = /* @__PURE__ */ Symbol("noofpi:doofpi");
240
+ function useDoofpi(options) {
241
+ const clients = inject3(DOOFPI_KEY, null);
242
+ if (!clients)
243
+ throw new Error(
244
+ "[noofpi] useDoofpi() must be called inside setup() or app.runWithContext()"
245
+ );
246
+ if (options?.mode) return clients.forMode(options.mode);
247
+ const path = clients.pending ?? inject3(routeLocationKey, null)?.path ?? "/";
248
+ return clients.forPath(path);
249
+ }
250
+ var browserBlocked = () => Promise.reject(
251
+ new Error(
252
+ '[noofpi] doofpi.fetch is "sfetch": doofpi requests are only allowed on the server'
253
+ )
254
+ );
255
+ function createDoofpiClients(config, rules, ctx) {
256
+ const clients = /* @__PURE__ */ new Map();
257
+ const forMode = (mode) => {
258
+ let client = clients.get(mode);
259
+ if (!client) {
260
+ client = createDoofpiClient({ ...config, fetch: mode }, ctx);
261
+ clients.set(mode, client);
262
+ }
263
+ return client;
264
+ };
265
+ return {
266
+ forPath: (pathname) => forMode(resolveFetchMode(config.fetch, rules, pathname)),
267
+ forMode(mode) {
268
+ if (!FETCH_MODES.includes(mode))
269
+ throw new Error(
270
+ `[noofpi] useDoofpi({ mode }) must be one of ${FETCH_MODES.join(", ")} (got "${String(mode)}")`
271
+ );
272
+ if (mode !== "lfetch" && !usesFetchMode(config.fetch, rules, mode))
273
+ throw new Error(
274
+ `[noofpi] useDoofpi({ mode: "${mode}" }) needs "${mode}" in the config: set doofpi.fetch or a routeRules[...].fetch to "${mode}"`
275
+ );
276
+ return forMode(mode);
277
+ }
278
+ };
279
+ }
280
+ function createDoofpiClient(config, ctx) {
281
+ const { server, origin } = ctx;
282
+ const cookie = server && ctx.cookie ? { headers: { cookie: ctx.cookie } } : void 0;
283
+ const track = (fetch) => ctx.log ? recordFetch(
284
+ fetch ?? ((input, init) => globalThis.fetch(input, init)),
285
+ ctx.log,
286
+ {
287
+ side: server ? "server" : "browser",
288
+ mode: config.fetch,
289
+ transport: fetch && fetch === ctx.fetch ? "in-process" : "http"
290
+ }
291
+ ) : fetch;
292
+ switch (config.fetch) {
293
+ case "dfetch":
294
+ return createClient({
295
+ url: config.url,
296
+ root: config.root,
297
+ fetch: track(void 0)
298
+ });
299
+ case "sfetch":
300
+ return createClient({
301
+ url: config.url ?? origin,
302
+ root: config.root,
303
+ fetch: track(server ? void 0 : browserBlocked)
304
+ });
305
+ case "pfetch":
306
+ return createClient({
307
+ url: origin,
308
+ root: PROXY_PREFIX + config.root,
309
+ init: cookie,
310
+ // On the server the proxy is called in-process, so the same proxy hook applies as in the browser
311
+ fetch: track(server ? ctx.fetch : void 0)
312
+ });
313
+ case "lfetch":
314
+ return createClient({
315
+ url: origin,
316
+ root: config.root,
317
+ init: cookie,
318
+ fetch: track(server ? ctx.fetch : void 0)
319
+ });
320
+ }
321
+ }
322
+
323
+ // src/runtime/head.ts
324
+ import {
325
+ getCurrentScope,
326
+ inject as inject4,
327
+ onScopeDispose,
328
+ shallowRef as shallowRef2,
329
+ toValue
330
+ } from "vue";
331
+ var HEAD_KEY = /* @__PURE__ */ Symbol("noofpi:head");
332
+ function createHeadManager(defaults) {
333
+ const entries = shallowRef2([]);
334
+ return {
335
+ add(input) {
336
+ const entry = { input };
337
+ entries.value = [...entries.value, entry];
338
+ return () => {
339
+ entries.value = entries.value.filter((other) => other !== entry);
340
+ };
341
+ },
342
+ resolve: () => resolveHead(
343
+ defaults,
344
+ entries.value.map((entry) => toValue(entry.input))
345
+ )
346
+ };
347
+ }
348
+ function useHead(input) {
349
+ const head = inject4(HEAD_KEY, null);
350
+ if (!head)
351
+ throw new Error("[noofpi] useHead() must be called inside setup()");
352
+ const remove = head.add(input);
353
+ if (getCurrentScope()) onScopeDispose(remove);
354
+ }
355
+ function setAttrs(element, attrs) {
356
+ const previous = element.getAttribute(HEAD_ATTRS_ATTR)?.split(" ") ?? [];
357
+ for (const name of previous)
358
+ if (name && !(name in attrs)) element.removeAttribute(name);
359
+ for (const [name, value] of Object.entries(attrs))
360
+ element.setAttribute(name, value);
361
+ element.setAttribute(HEAD_ATTRS_ATTR, Object.keys(attrs).join(" "));
362
+ }
363
+ function applyHeadToDocument(head) {
364
+ document.title = head.title;
365
+ for (const stale of document.head.querySelectorAll(`[${HEAD_TAG_ATTR}]`))
366
+ stale.remove();
367
+ const tags = [
368
+ ...head.meta.map((attrs) => [
369
+ "meta",
370
+ attrs
371
+ ]),
372
+ ...head.link.map((attrs) => [
373
+ "link",
374
+ attrs
375
+ ])
376
+ ];
377
+ if (head.meta.some((attrs) => attrs.name === "viewport"))
378
+ document.head.querySelector(`meta[name="viewport"]:not([${HEAD_TAG_ATTR}])`)?.remove();
379
+ for (const [name, attrs] of tags) {
380
+ const element = document.createElement(name);
381
+ for (const [key, value] of Object.entries(attrs))
382
+ element.setAttribute(key, value);
383
+ element.setAttribute(HEAD_TAG_ATTR, "");
384
+ document.head.append(element);
385
+ }
386
+ setAttrs(document.documentElement, head.htmlAttrs);
387
+ setAttrs(document.body, head.bodyAttrs);
388
+ }
389
+
390
+ // src/runtime/navigate.ts
391
+ import { hasInjectionContext, inject as inject5 } from "vue";
392
+ import {
393
+ routerKey
394
+ } from "vue-router";
395
+ var PARAM = /\/:(\w+)(?:\([^)]*\))?([*+?])?/g;
396
+ function fillRoutePath(pattern, params) {
397
+ const path = pattern.replace(PARAM, (_, name, modifier) => {
398
+ const value = params[name];
399
+ const optional = modifier === "*" || modifier === "?";
400
+ const parts = (Array.isArray(value) ? value : [value]).filter((part) => part !== void 0 && part !== "").map((part) => encodeURIComponent(String(part)));
401
+ if (!parts.length) {
402
+ if (optional) return "";
403
+ throw new Error(
404
+ `[noofpi] navigateTo("${pattern}") is missing the param "${name}"`
405
+ );
406
+ }
407
+ return "/" + parts.join("/");
408
+ });
409
+ return path || "/";
410
+ }
411
+ var browserRouter;
412
+ function setBrowserRouter(router) {
413
+ browserRouter = router;
414
+ }
415
+ function currentRouter() {
416
+ const router = (hasInjectionContext() ? inject5(routerKey, null) : null) ?? browserRouter;
417
+ if (!router)
418
+ throw new Error(
419
+ "[noofpi] navigateTo() must be called in the browser, inside setup() or inside app.runWithContext()"
420
+ );
421
+ return router;
422
+ }
423
+ function navigateTo(to, options = {}) {
424
+ const { params, replace, query, hash } = options;
425
+ let location2 = to;
426
+ if (typeof to === "string") {
427
+ const path = params ? fillRoutePath(to, params) : to;
428
+ location2 = query || hash ? { path, query, hash } : path;
429
+ } else if (query || hash) {
430
+ location2 = { ...to, ...query && { query }, ...hash && { hash } };
431
+ }
432
+ const router = currentRouter();
433
+ return replace ? router.replace(location2) : router.push(location2);
434
+ }
435
+
436
+ // src/runtime/plugins.ts
437
+ function defineNoofpiPlugin(plugin) {
438
+ return plugin;
439
+ }
440
+ function pluginMode(file) {
441
+ const base = file.slice(file.lastIndexOf("/") + 1).replace(/\.[jt]s$/, "");
442
+ if (base.endsWith(".client")) return "client";
443
+ if (base.endsWith(".server")) return "server";
444
+ return "both";
445
+ }
446
+ function runPlugins(modules, context) {
447
+ for (const [file, plugin] of Object.entries(modules).sort(
448
+ ([a], [b]) => a < b ? -1 : 1
449
+ )) {
450
+ const mode = pluginMode(file);
451
+ if (mode === "both" || mode === "server" === context.server)
452
+ plugin(context);
453
+ }
454
+ }
455
+
456
+ // src/runtime/state.ts
457
+ import { hasInjectionContext as hasInjectionContext2, inject as inject6, ref as ref3 } from "vue";
458
+ var registries = /* @__PURE__ */ new WeakMap();
459
+ function registryOf(payload) {
460
+ let registry = registries.get(payload);
461
+ if (!registry) registries.set(payload, registry = /* @__PURE__ */ new Map());
462
+ return registry;
463
+ }
464
+ var browserPayload;
465
+ function setBrowserState(payload) {
466
+ browserPayload = payload;
467
+ }
468
+ var serverPayload = () => void 0;
469
+ function setServerStateSource(source) {
470
+ serverPayload = source;
471
+ }
472
+ var currentPayload = () => (hasInjectionContext2() ? inject6(PAYLOAD_KEY, null) : null) ?? serverPayload() ?? browserPayload;
473
+ function collectState(payload) {
474
+ const state = {};
475
+ for (const [key, value] of registryOf(payload))
476
+ if (value.value !== void 0) state[key] = value.value;
477
+ return state;
478
+ }
479
+ function useState(key, init) {
480
+ const payload = currentPayload();
481
+ if (!payload)
482
+ throw new Error(
483
+ "[noofpi] useState() must be called while rendering a request or in the browser"
484
+ );
485
+ const registry = registryOf(payload);
486
+ let state = registry.get(key);
487
+ if (!state) {
488
+ const hydrated = !payload.server && payload.state && key in payload.state;
489
+ state = ref3(hydrated ? payload.state[key] : void 0);
490
+ registry.set(key, state);
491
+ }
492
+ if (state.value === void 0 && init) state.value = init();
493
+ return state;
494
+ }
495
+
496
+ // src/runtime/cookie.ts
497
+ import { customRef, inject as inject7 } from "vue";
498
+ var COOKIES_KEY = /* @__PURE__ */ Symbol("noofpi:cookies");
499
+ function createBrowserCookieJar() {
500
+ return createCookieJar({
501
+ cookie: () => document.cookie,
502
+ defaults: { secure: location.protocol === "https:" },
503
+ write: (header) => {
504
+ document.cookie = header;
505
+ }
506
+ });
507
+ }
508
+ function useCookies() {
509
+ const jar = inject7(COOKIES_KEY, null);
510
+ if (!jar)
511
+ throw new Error(
512
+ "[noofpi] useCookies() must be called inside setup() or app.runWithContext()"
513
+ );
514
+ return jar;
515
+ }
516
+ function useCookie(target, options = {}) {
517
+ const jar = useCookies();
518
+ const { default: getDefault, codec, ...cookieOptions } = options;
519
+ const cookie = typeof target === "string" ? { name: target, codec: codec ?? stringCodec, options: {} } : target;
520
+ const writeOptions = mergeCookieOptions(
521
+ { httpOnly: false },
522
+ cookie.options,
523
+ cookieOptions
524
+ );
525
+ let value = jar.get(cookie) ?? getDefault?.();
526
+ return customRef((track, trigger) => ({
527
+ get() {
528
+ track();
529
+ return value;
530
+ },
531
+ set(next) {
532
+ value = next;
533
+ if (next === void 0 || next === null)
534
+ jar.remove(cookie, {
535
+ path: writeOptions.path,
536
+ domain: writeOptions.domain
537
+ });
538
+ else jar.set(cookie, next, writeOptions);
539
+ trigger();
540
+ }
541
+ }));
542
+ }
543
+
544
+ // src/runtime/i18n.ts
545
+ import { inject as inject8, ref as ref4, shallowReactive } from "vue";
546
+ function defineMessages(messages) {
547
+ return messages;
548
+ }
549
+ var I18N_KEY = /* @__PURE__ */ Symbol("noofpi:i18n");
550
+ function catalogFromFiles(files, locales) {
551
+ const catalog = {};
552
+ for (const [file, value] of Object.entries(files)) {
553
+ const name = file.slice(file.lastIndexOf("/") + 1).replace(/\.[^.]+$/, "");
554
+ const locale = locales.find((candidate) => candidate === name);
555
+ if (locale) catalog[locale] = value;
556
+ }
557
+ return catalog;
558
+ }
559
+ function createI18n(options) {
560
+ const { config, cookies, loaders = {} } = options;
561
+ const catalog = shallowReactive({
562
+ ...options.catalog
563
+ });
564
+ const locale = ref4(options.locale);
565
+ const t = (key, params) => translate(catalog, locale.value, config.defaultLocale, key, params);
566
+ const loading = /* @__PURE__ */ new Map();
567
+ const load = (target) => {
568
+ const loader = loaders[target];
569
+ if (Object.hasOwn(catalog, target) || !loader) return Promise.resolve();
570
+ let pending = loading.get(target);
571
+ if (!pending) {
572
+ pending = loader().then((messages) => {
573
+ catalog[target] = messages;
574
+ }).finally(() => loading.delete(target));
575
+ loading.set(target, pending);
576
+ }
577
+ return pending;
578
+ };
579
+ const apply = (next) => {
580
+ locale.value = next;
581
+ cookies.set(LOCALE_COOKIE, next, {
582
+ maxAge: 60 * 60 * 24 * 365,
583
+ httpOnly: false
584
+ });
585
+ };
586
+ let latest = 0;
587
+ return {
588
+ locale,
589
+ locales: config.locales,
590
+ defaultLocale: config.defaultLocale,
591
+ t,
592
+ ready: Promise.all([load(config.defaultLocale), load(options.locale)]).then(
593
+ () => void 0
594
+ ),
595
+ setLocale(next) {
596
+ if (!config.locales.includes(next))
597
+ throw new Error(
598
+ `[noofpi] Unknown locale "${next}", expected one of ${config.locales.join(", ")}`
599
+ );
600
+ const request = ++latest;
601
+ if (Object.hasOwn(catalog, next) || !loaders[next]) {
602
+ apply(next);
603
+ return Promise.resolve();
604
+ }
605
+ return load(next).then(() => {
606
+ if (request === latest) apply(next);
607
+ });
608
+ }
609
+ };
610
+ }
611
+ function useI18n() {
612
+ const i18n = inject8(I18N_KEY, null);
613
+ if (!i18n)
614
+ throw new Error(
615
+ "[noofpi] useI18n() needs `i18n: { locales: [...] }` in noofpi.config.ts and must be called inside setup()"
616
+ );
617
+ return i18n;
618
+ }
619
+
620
+ // src/runtime/error.ts
621
+ import {
622
+ defineComponent,
623
+ h,
624
+ hasInjectionContext as hasInjectionContext3,
625
+ inject as inject9
626
+ } from "vue";
627
+ import { START_LOCATION } from "vue-router";
628
+ var ERROR_KEY = /* @__PURE__ */ Symbol("noofpi:error");
629
+ var browser;
630
+ var currentState = () => (hasInjectionContext3() ? inject9(ERROR_KEY, void 0) : void 0) ?? browser?.error;
631
+ var notFoundError = (url) => toErrorData(
632
+ createError({
633
+ statusCode: 404,
634
+ statusMessage: "Page Not Found",
635
+ message: `Page not found: ${url}`
636
+ }),
637
+ url
638
+ );
639
+ function useError() {
640
+ const state = currentState();
641
+ if (!state)
642
+ throw new Error("[noofpi] useError() must be called inside setup()");
643
+ return state;
644
+ }
645
+ function showError(error) {
646
+ const state = currentState();
647
+ if (!state)
648
+ throw new Error("[noofpi] showError() must be called inside setup()");
649
+ const created = isNoofpiError(error) ? error : createError(error);
650
+ state.value = toErrorData(created);
651
+ return created;
652
+ }
653
+ async function clearError(options = {}) {
654
+ const state = currentState();
655
+ if (!state)
656
+ throw new Error("[noofpi] clearError() must be called inside setup()");
657
+ state.value = null;
658
+ if (options.redirect !== void 0) {
659
+ if (!browser)
660
+ throw new Error("[noofpi] clearError() can only redirect in the browser");
661
+ await browser.router.push(options.redirect);
662
+ }
663
+ }
664
+ function createRootComponent(Root, ErrorPage2) {
665
+ return defineComponent({
666
+ name: "NoofpiRoot",
667
+ setup() {
668
+ const error = useError();
669
+ return () => error.value ? h(ErrorPage2, { error: error.value }) : h(Root);
670
+ }
671
+ });
672
+ }
673
+ function bindBrowserErrorPage(app, router, error) {
674
+ browser = { error, router };
675
+ const urlOf = () => location.pathname + location.search;
676
+ router.afterEach((to, from) => {
677
+ if (!to.matched.length) error.value = notFoundError(to.fullPath);
678
+ else if (from !== START_LOCATION) error.value = null;
679
+ });
680
+ router.onError((failure) => {
681
+ if (isNoofpiError(failure)) error.value = toErrorData(failure, urlOf());
682
+ });
683
+ app.config.errorHandler = (failure) => {
684
+ if (isNoofpiError(failure)) error.value = toErrorData(failure, urlOf());
685
+ else console.error(failure);
686
+ };
687
+ }
688
+
689
+ // src/runtime/app.ts
690
+ import { createApp, createSSRApp, ref as ref5, watch } from "vue";
691
+ import {
692
+ createMemoryHistory,
693
+ createRouter,
694
+ createWebHistory
695
+ } from "vue-router";
696
+ import { publicConfig, serverConfig } from "virtual:noofpi/config";
697
+ import routes from "virtual:noofpi/routes";
698
+ import routeMiddleware from "virtual:noofpi/middleware";
699
+ import appPlugins from "virtual:noofpi/plugins";
700
+ import AppRoot from "virtual:noofpi/app-root";
701
+ import ErrorPage from "virtual:noofpi/error";
702
+ import { i18nConfig, messageFiles, messageLoaders } from "virtual:noofpi/i18n";
703
+ function createNoofpiApp(ctx) {
704
+ const config = ctx.server ? serverConfig : publicConfig;
705
+ const hydrate = ctx.server || isServerRendered(config.ssr, config.routeRules, location.pathname);
706
+ const app = (hydrate ? createSSRApp : createApp)(
707
+ ErrorPage ? createRootComponent(AppRoot, ErrorPage) : AppRoot
708
+ );
709
+ const router = createRouter({
710
+ history: ctx.server ? createMemoryHistory() : createWebHistory(import.meta.env.BASE_URL),
711
+ routes
712
+ });
713
+ const log = import.meta.env.DEV && publicConfig.devtools ? createRequestLog() : void 0;
714
+ const clients = createDoofpiClients(config.doofpi, config.routeRules, {
715
+ ...ctx,
716
+ origin: ctx.origin ?? window.location.origin,
717
+ log
718
+ });
719
+ router.beforeEach((to) => {
720
+ clients.pending = to.path;
721
+ });
722
+ router.beforeEach(
723
+ createMiddlewareGuard(createMiddlewareRegistry(routeMiddleware))
724
+ );
725
+ const settle = () => {
726
+ clients.pending = void 0;
727
+ };
728
+ router.afterEach(settle);
729
+ router.onError(settle);
730
+ app.use(router);
731
+ if (!ctx.server) setBrowserRouter(router);
732
+ const cookies = ctx.cookies ?? (ctx.server ? createCookieJar({ cookie: ctx.cookie }) : createBrowserCookieJar());
733
+ app.provide(COOKIES_KEY, cookies);
734
+ app.provide(DOOFPI_KEY, clients);
735
+ const payload = ctx.server ? { server: true, data: {}, errors: {} } : {
736
+ server: false,
737
+ ...hydrate ? readPayload() : { data: {}, errors: {} }
738
+ };
739
+ app.provide(PAYLOAD_KEY, payload);
740
+ const loaders = installLoaders(router, {
741
+ payload,
742
+ run: (to, call) => {
743
+ const previous = clients.pending;
744
+ clients.pending = to.path;
745
+ try {
746
+ return app.runWithContext(call);
747
+ } finally {
748
+ clients.pending = previous;
749
+ }
750
+ }
751
+ });
752
+ app.provide(LOADER_KEY, loaders.state);
753
+ if (!ctx.server) setBrowserState(payload);
754
+ if (log && payload.requests) addEntries(log, payload.requests);
755
+ const error = ref5(payload.error ?? null);
756
+ app.provide(ERROR_KEY, error);
757
+ if (ErrorPage && !ctx.server) bindBrowserErrorPage(app, router, error);
758
+ let i18n;
759
+ if (i18nConfig) {
760
+ const rendered = !ctx.server && hydrate ? matchLocale([payload.locale], i18nConfig.locales) : void 0;
761
+ i18n = createI18n({
762
+ config: i18nConfig,
763
+ catalog: catalogFromFiles(messageFiles, i18nConfig.locales),
764
+ loaders: catalogFromFiles(messageLoaders, i18nConfig.locales),
765
+ locale: rendered ?? pickLocale(i18nConfig, {
766
+ saved: cookies.get(LOCALE_COOKIE),
767
+ preferred: ctx.server ? parseAcceptLanguage(ctx.acceptLanguage) : navigator.languages
768
+ }),
769
+ cookies
770
+ });
771
+ app.provide(I18N_KEY, i18n);
772
+ app.config.globalProperties.$t = i18n.t;
773
+ }
774
+ const head = createHeadManager(config.head);
775
+ app.provide(HEAD_KEY, head);
776
+ if (i18n) {
777
+ const { locale } = i18n;
778
+ head.add(() => ({
779
+ htmlAttrs: { lang: locale.value, dir: textDirection(locale.value) }
780
+ }));
781
+ }
782
+ if (!ctx.server)
783
+ watch(() => head.resolve(), applyHeadToDocument, { flush: "post" });
784
+ runPlugins(appPlugins, { app, router, server: !!ctx.server });
785
+ return { app, router, payload, head, error, log, i18n, loaders };
786
+ }
787
+
788
+ export {
789
+ useAsyncData,
790
+ definePage,
791
+ useLoaderData,
792
+ snapshotEntries,
793
+ useDoofpi,
794
+ createDoofpiClient,
795
+ useHead,
796
+ navigateTo,
797
+ defineNoofpiPlugin,
798
+ setServerStateSource,
799
+ collectState,
800
+ useState,
801
+ useCookies,
802
+ useCookie,
803
+ defineMessages,
804
+ useI18n,
805
+ notFoundError,
806
+ useError,
807
+ showError,
808
+ clearError,
809
+ createNoofpiApp
810
+ };