@emulators/adapter-nuxt 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,7 +24,7 @@ import { createEmulateHandler } from '@emulators/adapter-nuxt'
24
24
  import * as github from '@emulators/github'
25
25
  import * as google from '@emulators/google'
26
26
 
27
- export default defineEventHandler(createEmulateHandler({
27
+ export const emulator = createEmulateHandler({
28
28
  services: {
29
29
  github: {
30
30
  emulator: github,
@@ -40,7 +40,9 @@ export default defineEventHandler(createEmulateHandler({
40
40
  },
41
41
  },
42
42
  },
43
- }))
43
+ })
44
+
45
+ export default defineEventHandler(emulator)
44
46
  ```
45
47
 
46
48
  This creates these routes:
@@ -48,6 +50,10 @@ This creates these routes:
48
50
  - `/emulate/github/**` serves the GitHub emulator
49
51
  - `/emulate/google/**` serves the Google emulator
50
52
 
53
+ GitHub App seeds may omit `private_key`. Read generated keys with the handler's server-only `generatedSecrets()` method. Explicit keys are excluded; persisted snapshots contain generated keys and require a private backend with atomic `initialize`.
54
+
55
+ Inspect minted installation-token metadata at `/emulate/github/_emulate/installation-tokens`.
56
+
51
57
  ## Nuxt Config
52
58
 
53
59
  Emulator UI pages use bundled fonts. Wrap your Nuxt config so Nitro traces the core package assets into production builds:
package/dist/index.d.ts CHANGED
@@ -1,28 +1,12 @@
1
- import { ServicePlugin, Store, WebhookDispatcher, AppKeyResolver, PersistenceAdapter } from '@emulators/core';
2
- export { PersistenceAdapter } from '@emulators/core';
1
+ import { AdapterHandlerConfig, AdapterEmulatorEntry, AdapterEmulatorModule, GeneratedSecret } from '@emulators/core';
2
+ export { GeneratedSecret, PersistenceAdapter, PreparedServiceSeed } from '@emulators/core';
3
+
4
+ type EmulatorModule = AdapterEmulatorModule;
5
+ type EmulatorEntry = AdapterEmulatorEntry;
6
+ type EmulateHandlerConfig = AdapterHandlerConfig;
3
7
 
4
- interface EmulatorModule {
5
- plugin?: ServicePlugin;
6
- default?: ServicePlugin;
7
- seedFromConfig?(store: Store, baseUrl: string, config: unknown, webhooks?: WebhookDispatcher): void;
8
- createAppKeyResolver?(store: Store): AppKeyResolver;
9
- }
10
- interface EmulatorEntry {
11
- emulator: EmulatorModule;
12
- seed?: Record<string, unknown>;
13
- }
14
- interface EmulateHandlerConfig {
15
- services: Record<string, EmulatorEntry>;
16
- persistence?: PersistenceAdapter;
17
- }
18
8
  interface NuxtAdapterOptions {
19
- /**
20
- * Named catch-all route param from `server/routes/emulate/[...path].ts`.
21
- */
22
9
  param?: string;
23
- /**
24
- * Explicit mount path. Usually detected from the request URL.
25
- */
26
10
  routePrefix?: string;
27
11
  }
28
12
  type HeaderValue = string | string[] | number | undefined;
@@ -41,7 +25,10 @@ interface NuxtEventLike {
41
25
  path?: string;
42
26
  };
43
27
  }
44
- declare function createEmulateHandler(config: EmulateHandlerConfig, options?: NuxtAdapterOptions): (event: NuxtEventLike) => Promise<Response>;
28
+ declare function createEmulateHandler(config: EmulateHandlerConfig, options?: NuxtAdapterOptions): {
29
+ (event: NuxtEventLike): Promise<Response>;
30
+ generatedSecrets: () => Promise<readonly GeneratedSecret[]>;
31
+ };
45
32
  declare function withEmulate<T>(nuxtConfig: T): T;
46
33
 
47
- export { type EmulateHandlerConfig, type EmulatorModule, type NuxtAdapterOptions, type NuxtEventLike, createEmulateHandler, withEmulate };
34
+ export { type EmulateHandlerConfig, type EmulatorEntry, type EmulatorModule, type NuxtAdapterOptions, type NuxtEventLike, createEmulateHandler, withEmulate };
package/dist/index.js CHANGED
@@ -1,315 +1,104 @@
1
1
  // src/index.ts
2
- import { createRequire } from "module";
3
2
  import { cpSync } from "fs";
3
+ import { createRequire } from "module";
4
4
  import { dirname, join } from "path";
5
5
  import {
6
- createServer,
7
- debug,
8
- serializeTokenMap,
9
- restoreTokenMap
6
+ createAdapterRuntime,
7
+ debug
10
8
  } from "@emulators/core";
11
- var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
12
- function resolvePlugin(mod) {
13
- const plugin = mod.plugin ?? mod.default;
14
- if (!plugin) {
15
- throw new Error("Emulator module must export `plugin` or a default export implementing ServicePlugin");
16
- }
17
- return plugin;
18
- }
19
- function takeSnapshot(apps) {
20
- const mergedStore = { collections: {}, data: {} };
21
- const tokens = {};
22
- for (const [name, sa] of apps) {
23
- const snap = sa.store.snapshot();
24
- for (const [colName, colSnap] of Object.entries(snap.collections)) {
25
- mergedStore.collections[`${name}:${colName}`] = colSnap;
26
- }
27
- for (const [key, val] of Object.entries(snap.data)) {
28
- mergedStore.data[`${name}:${key}`] = val;
29
- }
30
- tokens[name] = serializeTokenMap(sa.tokenMap);
31
- }
32
- return { store: mergedStore, tokens };
33
- }
34
- function restoreFromSnapshot(apps, snapshot) {
35
- const storesByName = /* @__PURE__ */ new Map();
36
- for (const [qualifiedName, colSnap] of Object.entries(snapshot.store.collections)) {
37
- const sepIdx = qualifiedName.indexOf(":");
38
- const name = qualifiedName.slice(0, sepIdx);
39
- const colName = qualifiedName.slice(sepIdx + 1);
40
- if (!storesByName.has(name)) {
41
- storesByName.set(name, { collections: {}, data: {} });
42
- }
43
- storesByName.get(name).collections[colName] = colSnap;
44
- }
45
- for (const [qualifiedKey, val] of Object.entries(snapshot.store.data)) {
46
- const sepIdx = qualifiedKey.indexOf(":");
47
- const name = qualifiedKey.slice(0, sepIdx);
48
- const dataKey = qualifiedKey.slice(sepIdx + 1);
49
- if (!storesByName.has(name)) {
50
- storesByName.set(name, { collections: {}, data: {} });
51
- }
52
- storesByName.get(name).data[dataKey] = val;
53
- }
54
- for (const [name, sa] of apps) {
55
- const snap = storesByName.get(name);
56
- if (snap) {
57
- sa.store.restore(snap);
58
- }
59
- restoreTokenMap(sa.tokenMap, snapshot.tokens[name] ?? []);
60
- }
61
- }
62
- function normalizeRoutePrefix(prefix) {
63
- const withLeadingSlash = prefix.startsWith("/") ? prefix : `/${prefix}`;
64
- return withLeadingSlash.replace(/\/+$/, "") || "/";
9
+ function normalizePrefix(prefix) {
10
+ return (prefix.startsWith("/") ? prefix : `/${prefix}`).replace(/\/+$/, "") || "/";
65
11
  }
66
12
  function joinPath(base, segment) {
67
13
  return base === "/" ? `/${segment}` : `${base}/${segment}`;
68
14
  }
69
- function detectPrefix(url, pathSegments) {
70
- const parsed = new URL(url);
71
- const fullPath = parsed.pathname;
72
- const restPath = "/" + pathSegments.join("/");
73
- const idx = fullPath.lastIndexOf(restPath);
74
- if (idx >= 0) {
75
- return fullPath.slice(0, idx) || "/";
76
- }
77
- throw new Error(`Could not detect mount path from URL: ${url}`);
78
- }
79
15
  function splitPath(path) {
80
16
  return path.split("/").filter(Boolean);
81
17
  }
82
- function getPathSegments(event, paramName, routePrefix) {
18
+ function getPathSegments(event, param, routePrefix) {
83
19
  const params = event.context?.params ?? {};
84
- const value = params[paramName] ?? params._ ?? params.path;
85
- if (Array.isArray(value)) {
86
- return value.flatMap((part) => splitPath(String(part)));
87
- }
88
- if (typeof value === "string" && value.length > 0) {
89
- return splitPath(value);
90
- }
20
+ const value = params[param] ?? params._ ?? params.path;
21
+ if (Array.isArray(value)) return value.flatMap((part) => splitPath(String(part)));
22
+ if (typeof value === "string" && value) return splitPath(value);
91
23
  if (routePrefix && event.context?.path) {
92
- const prefix = normalizeRoutePrefix(routePrefix);
93
- const path = event.context.path.startsWith(prefix) ? event.context.path.slice(prefix.length) : event.context.path;
94
- return splitPath(path);
24
+ const path = event.context.path;
25
+ return splitPath(path.startsWith(routePrefix) ? path.slice(routePrefix.length) : path);
95
26
  }
96
27
  return [];
97
28
  }
98
29
  function firstHeader(value) {
99
30
  const raw = Array.isArray(value) ? value[0] : value;
100
- if (raw === void 0) return void 0;
101
- return String(raw).split(",")[0]?.trim();
102
- }
103
- function headersFromNode(headers) {
104
- const result = new Headers();
105
- for (const [key, value] of Object.entries(headers ?? {})) {
106
- if (value === void 0) continue;
107
- if (Array.isArray(value)) {
108
- for (const item of value) {
109
- result.append(key, item);
110
- }
111
- continue;
112
- }
113
- result.set(key, String(value));
114
- }
115
- return result;
116
- }
117
- function isWebRequest(value) {
118
- if (typeof value !== "object" || value === null) return false;
119
- const candidate = value;
120
- return typeof candidate.url === "string" && typeof candidate.method === "string" && typeof candidate.headers?.get === "function";
31
+ return raw === void 0 ? void 0 : String(raw).split(",")[0]?.trim();
121
32
  }
122
33
  function requestFromEvent(event) {
123
- if (isWebRequest(event.req)) {
34
+ if (event.req && typeof event.req.url === "string" && typeof event.req.method === "string" && typeof event.req.headers?.get === "function") {
124
35
  return event.req;
125
36
  }
126
- const nodeReq = event.node?.req;
127
- if (!nodeReq) {
128
- throw new Error("Nuxt event must provide `req` or `node.req`");
129
- }
130
- const headers = nodeReq.headers ?? {};
131
- const proto = firstHeader(headers["x-forwarded-proto"]) ?? "http";
132
- const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers.host) ?? "localhost";
133
- const url = new URL(nodeReq.url ?? "/", `${proto}://${host}`);
134
- const method = nodeReq.method ?? "GET";
135
- const init = {
136
- method,
137
- headers: headersFromNode(headers)
138
- };
37
+ const nodeRequest = event.node?.req;
38
+ if (!nodeRequest) throw new Error("Nuxt event must provide `req` or `node.req`");
39
+ const sourceHeaders = nodeRequest.headers ?? {};
40
+ const protocol = firstHeader(sourceHeaders["x-forwarded-proto"]) ?? "http";
41
+ const host = firstHeader(sourceHeaders["x-forwarded-host"]) ?? firstHeader(sourceHeaders.host) ?? "localhost";
42
+ const headers = new Headers();
43
+ for (const [name, value] of Object.entries(sourceHeaders)) {
44
+ if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));
45
+ else if (value !== void 0) headers.set(name, String(value));
46
+ }
47
+ const method = nodeRequest.method ?? "GET";
48
+ const init = { method, headers };
139
49
  if (method !== "GET" && method !== "HEAD") {
140
- init.body = nodeReq;
50
+ init.body = nodeRequest;
141
51
  init.duplex = "half";
142
52
  }
143
- return new Request(url, init);
53
+ return new Request(new URL(nodeRequest.url ?? "/", `${protocol}://${host}`), init);
144
54
  }
145
- async function rewriteResponse(response, servicePrefix) {
146
- const contentType = response.headers.get("Content-Type") ?? "";
147
- const location = response.headers.get("Location");
148
- const isHtml = contentType.includes("text/html");
149
- const locationChanged = location != null && location.startsWith("/");
150
- if (!isHtml) {
151
- if (!locationChanged) return response;
152
- const headers2 = new Headers(response.headers);
153
- headers2.set("Location", servicePrefix + location);
154
- return new Response(response.body, {
155
- status: response.status,
156
- statusText: response.statusText,
157
- headers: headers2
158
- });
159
- }
160
- let html = await response.text();
161
- html = html.replace(/(action|href)="(\/[^"]*?)"/g, (_match, attr, path) => {
162
- if (path.startsWith(servicePrefix)) return `${attr}="${path}"`;
163
- return `${attr}="${servicePrefix}${path}"`;
164
- });
165
- html = html.replace(/url\('(\/[^']*?)'\)/g, (_match, path) => {
166
- if (path.startsWith(servicePrefix)) return `url('${path}')`;
167
- return `url('${servicePrefix}${path}')`;
168
- });
169
- const headers = new Headers(response.headers);
170
- if (locationChanged) {
171
- headers.set("Location", servicePrefix + location);
172
- }
173
- headers.delete("Content-Length");
174
- return new Response(html, {
175
- status: response.status,
176
- statusText: response.statusText,
177
- headers
178
- });
55
+ function detectPrefix(url, pathSegments) {
56
+ const pathname = new URL(url).pathname;
57
+ const index = pathname.lastIndexOf("/" + pathSegments.join("/"));
58
+ if (index >= 0) return pathname.slice(0, index) || "/";
59
+ throw new Error(`Could not detect mount path from URL: ${url}`);
179
60
  }
180
61
  function createEmulateHandler(config, options = {}) {
181
- const { services: serviceEntries, persistence } = config;
182
- const paramName = options.param ?? "path";
183
- const configuredMountPath = options.routePrefix ? normalizeRoutePrefix(options.routePrefix) : null;
184
- let apps = null;
62
+ const param = options.param ?? "path";
63
+ const configuredMountPath = options.routePrefix ? normalizePrefix(options.routePrefix) : null;
64
+ const runtime = createAdapterRuntime(config, joinPath);
185
65
  let mountPath = configuredMountPath;
186
- let initPromise = null;
187
- let pendingSave = Promise.resolve();
188
- function enqueueSave(targetApps = apps) {
189
- if (!persistence || !targetApps) return;
190
- pendingSave = pendingSave.then(async () => {
191
- const snapshot = takeSnapshot(targetApps);
192
- const json = JSON.stringify(snapshot);
193
- try {
194
- await persistence.save(json);
195
- } catch (err) {
196
- debug("persistence", "save failed: %o", err);
197
- }
198
- });
199
- }
200
- async function initApps(origin, mountPath2) {
201
- const serviceApps = /* @__PURE__ */ new Map();
202
- for (const [name, entry] of Object.entries(serviceEntries)) {
203
- const plugin = resolvePlugin(entry.emulator);
204
- const servicePrefix = joinPath(mountPath2, name);
205
- const baseUrl = `${origin}${servicePrefix}`;
206
- let appKeyResolver;
207
- const { app, store, tokenMap, webhooks } = createServer(plugin, {
208
- baseUrl,
209
- appKeyResolver: entry.emulator.createAppKeyResolver ? (appId) => appKeyResolver(appId) : void 0
210
- });
211
- if (entry.emulator.createAppKeyResolver) {
212
- appKeyResolver = entry.emulator.createAppKeyResolver(store);
213
- }
214
- serviceApps.set(name, { app, store, tokenMap, plugin, webhooks });
215
- }
216
- let restored = false;
217
- if (persistence) {
218
- const raw = await persistence.load();
219
- if (raw) {
220
- try {
221
- const snapshot = JSON.parse(raw);
222
- restoreFromSnapshot(serviceApps, snapshot);
223
- restored = true;
224
- } catch {
225
- }
226
- }
227
- }
228
- if (!restored) {
229
- for (const [name, entry] of Object.entries(serviceEntries)) {
230
- const sa = serviceApps.get(name);
231
- const servicePrefix = joinPath(mountPath2, name);
232
- const baseUrl = `${origin}${servicePrefix}`;
233
- sa.plugin.seed?.(sa.store, baseUrl);
234
- if (entry.seed && entry.emulator.seedFromConfig) {
235
- entry.emulator.seedFromConfig(sa.store, baseUrl, entry.seed, sa.webhooks);
236
- }
237
- }
238
- if (persistence) {
239
- enqueueSave(serviceApps);
240
- }
241
- }
242
- return serviceApps;
243
- }
244
- async function ensureInit(req, pathSegments) {
245
- if (apps) return apps;
246
- if (!initPromise) {
247
- const url = new URL(req.url);
248
- const origin = url.origin;
249
- mountPath = configuredMountPath ?? detectPrefix(req.url, pathSegments);
250
- initPromise = initApps(origin, mountPath).then((result) => {
251
- apps = result;
252
- });
253
- }
254
- await initPromise;
255
- return apps;
256
- }
257
- return async function emulateNuxtHandler(event) {
258
- const req = requestFromEvent(event);
259
- const pathSegments = getPathSegments(event, paramName, configuredMountPath ?? void 0);
260
- if (pathSegments.length === 0) {
261
- return new Response("Not found", { status: 404 });
262
- }
263
- const serviceApps = await ensureInit(req, pathSegments);
264
- const serviceName = pathSegments[0];
265
- const sa = serviceApps.get(serviceName);
266
- if (!sa) {
267
- return new Response(`Unknown service: ${serviceName}`, { status: 404 });
268
- }
269
- const restPath = "/" + pathSegments.slice(1).join("/");
270
- const url = new URL(req.url);
271
- const strippedUrl = new URL(restPath + url.search, url.origin);
272
- const strippedReq = new Request(strippedUrl.toString(), {
273
- method: req.method,
274
- headers: req.headers,
275
- body: req.body,
276
- duplex: "half"
277
- });
278
- let response = await sa.app.fetch(strippedReq);
279
- const servicePrefix = joinPath(mountPath, serviceName);
280
- response = await rewriteResponse(response, servicePrefix);
281
- if (persistence && MUTATING_METHODS.has(req.method)) {
282
- enqueueSave();
283
- }
284
- return response;
66
+ const handler = async (event) => {
67
+ const request = requestFromEvent(event);
68
+ const path = getPathSegments(event, param, configuredMountPath ?? void 0);
69
+ if (path.length === 0) return new Response("Not found", { status: 404 });
70
+ mountPath ??= detectPrefix(request.url, path);
71
+ return runtime.handle(request, path, mountPath);
285
72
  };
73
+ handler.generatedSecrets = runtime.generatedSecrets;
74
+ return handler;
286
75
  }
287
76
  function copyCoreFonts(nitro) {
288
77
  const serverDir = nitro.options?.output?.serverDir;
289
78
  if (!serverDir) return;
290
79
  try {
291
- const require2 = createRequire(import.meta.url);
292
- const corePkg = require2.resolve("@emulators/core/package.json");
293
- const fontsDir = join(dirname(corePkg), "dist", "fonts");
294
- cpSync(fontsDir, join(serverDir, "fonts"), { recursive: true });
295
- } catch (err) {
296
- debug("nuxt", "font copy failed: %o", err);
80
+ const corePackage = createRequire(import.meta.url).resolve("@emulators/core/package.json");
81
+ cpSync(join(dirname(corePackage), "dist", "fonts"), join(serverDir, "fonts"), { recursive: true });
82
+ } catch (error) {
83
+ debug("nuxt", "font copy failed: %o", error);
297
84
  }
298
85
  }
299
86
  function withEmulate(nuxtConfig) {
300
87
  const config = nuxtConfig;
301
88
  const nitro = { ...config.nitro ?? {} };
302
- const existingHooks = nitro.hooks ?? {};
303
- const prevCompiled = existingHooks.compiled;
304
- const compiled = async (nitroInstance) => {
305
- if (prevCompiled) await prevCompiled(nitroInstance);
306
- copyCoreFonts(nitroInstance);
307
- };
89
+ const hooks = nitro.hooks ?? {};
90
+ const previous = hooks.compiled;
308
91
  return {
309
92
  ...config,
310
93
  nitro: {
311
94
  ...nitro,
312
- hooks: { ...existingHooks, compiled }
95
+ hooks: {
96
+ ...hooks,
97
+ async compiled(instance) {
98
+ if (previous) await previous(instance);
99
+ copyCoreFonts(instance);
100
+ }
101
+ }
313
102
  }
314
103
  };
315
104
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { cpSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport {\n createServer,\n debug,\n serializeTokenMap,\n restoreTokenMap,\n type ServicePlugin,\n type Store,\n type TokenMap,\n type TokenEntry,\n type StoreSnapshot,\n type PersistenceAdapter,\n type AppKeyResolver,\n type WebhookDispatcher,\n} from \"@emulators/core\";\n\nexport type { PersistenceAdapter } from \"@emulators/core\";\n\nexport interface EmulatorModule {\n plugin?: ServicePlugin;\n default?: ServicePlugin;\n seedFromConfig?(store: Store, baseUrl: string, config: unknown, webhooks?: WebhookDispatcher): void;\n createAppKeyResolver?(store: Store): AppKeyResolver;\n}\n\ninterface EmulatorEntry {\n emulator: EmulatorModule;\n seed?: Record<string, unknown>;\n}\n\nexport interface EmulateHandlerConfig {\n services: Record<string, EmulatorEntry>;\n persistence?: PersistenceAdapter;\n}\n\nexport interface NuxtAdapterOptions {\n /**\n * Named catch-all route param from `server/routes/emulate/[...path].ts`.\n */\n param?: string;\n /**\n * Explicit mount path. Usually detected from the request URL.\n */\n routePrefix?: string;\n}\n\ntype HeaderValue = string | string[] | number | undefined;\n\ninterface NodeRequestLike {\n method?: string;\n url?: string;\n headers?: Record<string, HeaderValue>;\n}\n\nexport interface NuxtEventLike {\n req?: Request;\n node?: {\n req?: NodeRequestLike;\n };\n context?: {\n params?: Record<string, unknown>;\n path?: string;\n };\n}\n\ninterface Fetchable {\n fetch(request: Request, ...rest: unknown[]): Response | Promise<Response>;\n}\n\ninterface ServiceApp {\n app: Fetchable;\n store: Store;\n tokenMap: TokenMap;\n plugin: ServicePlugin;\n webhooks: WebhookDispatcher;\n}\n\ninterface FullSnapshot {\n store: StoreSnapshot;\n tokens: Record<string, TokenEntry[]>;\n}\n\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction resolvePlugin(mod: EmulatorModule): ServicePlugin {\n const plugin = mod.plugin ?? mod.default;\n if (!plugin) {\n throw new Error(\"Emulator module must export `plugin` or a default export implementing ServicePlugin\");\n }\n return plugin;\n}\n\nfunction takeSnapshot(apps: Map<string, ServiceApp>): FullSnapshot {\n const mergedStore: StoreSnapshot = { collections: {}, data: {} };\n const tokens: Record<string, TokenEntry[]> = {};\n\n for (const [name, sa] of apps) {\n const snap = sa.store.snapshot();\n for (const [colName, colSnap] of Object.entries(snap.collections)) {\n mergedStore.collections[`${name}:${colName}`] = colSnap;\n }\n for (const [key, val] of Object.entries(snap.data)) {\n mergedStore.data[`${name}:${key}`] = val;\n }\n tokens[name] = serializeTokenMap(sa.tokenMap);\n }\n\n return { store: mergedStore, tokens };\n}\n\nfunction restoreFromSnapshot(apps: Map<string, ServiceApp>, snapshot: FullSnapshot): void {\n const storesByName = new Map<string, StoreSnapshot>();\n for (const [qualifiedName, colSnap] of Object.entries(snapshot.store.collections)) {\n const sepIdx = qualifiedName.indexOf(\":\");\n const name = qualifiedName.slice(0, sepIdx);\n const colName = qualifiedName.slice(sepIdx + 1);\n if (!storesByName.has(name)) {\n storesByName.set(name, { collections: {}, data: {} });\n }\n storesByName.get(name)!.collections[colName] = colSnap;\n }\n for (const [qualifiedKey, val] of Object.entries(snapshot.store.data)) {\n const sepIdx = qualifiedKey.indexOf(\":\");\n const name = qualifiedKey.slice(0, sepIdx);\n const dataKey = qualifiedKey.slice(sepIdx + 1);\n if (!storesByName.has(name)) {\n storesByName.set(name, { collections: {}, data: {} });\n }\n storesByName.get(name)!.data[dataKey] = val;\n }\n\n for (const [name, sa] of apps) {\n const snap = storesByName.get(name);\n if (snap) {\n sa.store.restore(snap);\n }\n restoreTokenMap(sa.tokenMap, snapshot.tokens[name] ?? []);\n }\n}\n\nfunction normalizeRoutePrefix(prefix: string): string {\n const withLeadingSlash = prefix.startsWith(\"/\") ? prefix : `/${prefix}`;\n return withLeadingSlash.replace(/\\/+$/, \"\") || \"/\";\n}\n\nfunction joinPath(base: string, segment: string): string {\n return base === \"/\" ? `/${segment}` : `${base}/${segment}`;\n}\n\nfunction detectPrefix(url: string, pathSegments: string[]): string {\n const parsed = new URL(url);\n const fullPath = parsed.pathname;\n const restPath = \"/\" + pathSegments.join(\"/\");\n const idx = fullPath.lastIndexOf(restPath);\n if (idx >= 0) {\n return fullPath.slice(0, idx) || \"/\";\n }\n throw new Error(`Could not detect mount path from URL: ${url}`);\n}\n\nfunction splitPath(path: string): string[] {\n return path.split(\"/\").filter(Boolean);\n}\n\nfunction getPathSegments(event: NuxtEventLike, paramName: string, routePrefix?: string): string[] {\n const params = event.context?.params ?? {};\n const value = params[paramName] ?? params._ ?? params.path;\n\n if (Array.isArray(value)) {\n return value.flatMap((part) => splitPath(String(part)));\n }\n if (typeof value === \"string\" && value.length > 0) {\n return splitPath(value);\n }\n\n if (routePrefix && event.context?.path) {\n const prefix = normalizeRoutePrefix(routePrefix);\n const path = event.context.path.startsWith(prefix) ? event.context.path.slice(prefix.length) : event.context.path;\n return splitPath(path);\n }\n\n return [];\n}\n\nfunction firstHeader(value: HeaderValue): string | undefined {\n const raw = Array.isArray(value) ? value[0] : value;\n if (raw === undefined) return undefined;\n return String(raw).split(\",\")[0]?.trim();\n}\n\nfunction headersFromNode(headers: Record<string, HeaderValue> | undefined): Headers {\n const result = new Headers();\n for (const [key, value] of Object.entries(headers ?? {})) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const item of value) {\n result.append(key, item);\n }\n continue;\n }\n result.set(key, String(value));\n }\n return result;\n}\n\nfunction isWebRequest(value: unknown): value is Request {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as Request;\n return (\n typeof candidate.url === \"string\" &&\n typeof candidate.method === \"string\" &&\n typeof candidate.headers?.get === \"function\"\n );\n}\n\nfunction requestFromEvent(event: NuxtEventLike): Request {\n if (isWebRequest(event.req)) {\n return event.req;\n }\n\n const nodeReq = event.node?.req;\n if (!nodeReq) {\n throw new Error(\"Nuxt event must provide `req` or `node.req`\");\n }\n\n const headers = nodeReq.headers ?? {};\n const proto = firstHeader(headers[\"x-forwarded-proto\"]) ?? \"http\";\n const host = firstHeader(headers[\"x-forwarded-host\"]) ?? firstHeader(headers.host) ?? \"localhost\";\n const url = new URL(nodeReq.url ?? \"/\", `${proto}://${host}`);\n const method = nodeReq.method ?? \"GET\";\n const init: RequestInit & { duplex?: string } = {\n method,\n headers: headersFromNode(headers),\n };\n\n if (method !== \"GET\" && method !== \"HEAD\") {\n init.body = nodeReq as unknown as RequestInit[\"body\"];\n init.duplex = \"half\";\n }\n\n return new Request(url, init);\n}\n\nasync function rewriteResponse(response: Response, servicePrefix: string): Promise<Response> {\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n const location = response.headers.get(\"Location\");\n const isHtml = contentType.includes(\"text/html\");\n const locationChanged = location != null && location.startsWith(\"/\");\n\n if (!isHtml) {\n if (!locationChanged) return response;\n const headers = new Headers(response.headers);\n headers.set(\"Location\", servicePrefix + location);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n let html = await response.text();\n\n html = html.replace(/(action|href)=\"(\\/[^\"]*?)\"/g, (_match, attr, path) => {\n if (path.startsWith(servicePrefix)) return `${attr}=\"${path}\"`;\n return `${attr}=\"${servicePrefix}${path}\"`;\n });\n\n html = html.replace(/url\\('(\\/[^']*?)'\\)/g, (_match, path) => {\n if (path.startsWith(servicePrefix)) return `url('${path}')`;\n return `url('${servicePrefix}${path}')`;\n });\n\n const headers = new Headers(response.headers);\n if (locationChanged) {\n headers.set(\"Location\", servicePrefix + location);\n }\n headers.delete(\"Content-Length\");\n\n return new Response(html, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nexport function createEmulateHandler(config: EmulateHandlerConfig, options: NuxtAdapterOptions = {}) {\n const { services: serviceEntries, persistence } = config;\n const paramName = options.param ?? \"path\";\n const configuredMountPath = options.routePrefix ? normalizeRoutePrefix(options.routePrefix) : null;\n\n let apps: Map<string, ServiceApp> | null = null;\n let mountPath: string | null = configuredMountPath;\n let initPromise: Promise<void> | null = null;\n let pendingSave: Promise<void> = Promise.resolve();\n\n function enqueueSave(targetApps: Map<string, ServiceApp> | null = apps): void {\n if (!persistence || !targetApps) return;\n pendingSave = pendingSave.then(async () => {\n const snapshot = takeSnapshot(targetApps);\n const json = JSON.stringify(snapshot);\n try {\n await persistence.save(json);\n } catch (err) {\n debug(\"persistence\", \"save failed: %o\", err);\n }\n });\n }\n\n async function initApps(origin: string, mountPath: string): Promise<Map<string, ServiceApp>> {\n const serviceApps = new Map<string, ServiceApp>();\n\n for (const [name, entry] of Object.entries(serviceEntries)) {\n const plugin = resolvePlugin(entry.emulator);\n const servicePrefix = joinPath(mountPath, name);\n const baseUrl = `${origin}${servicePrefix}`;\n\n let appKeyResolver: AppKeyResolver | undefined;\n const { app, store, tokenMap, webhooks } = createServer(plugin, {\n baseUrl,\n appKeyResolver: entry.emulator.createAppKeyResolver ? (appId) => appKeyResolver!(appId) : undefined,\n });\n\n if (entry.emulator.createAppKeyResolver) {\n appKeyResolver = entry.emulator.createAppKeyResolver(store);\n }\n\n serviceApps.set(name, { app, store, tokenMap, plugin, webhooks });\n }\n\n let restored = false;\n if (persistence) {\n const raw = await persistence.load();\n if (raw) {\n try {\n const snapshot = JSON.parse(raw) as FullSnapshot;\n restoreFromSnapshot(serviceApps, snapshot);\n restored = true;\n } catch {\n // Corrupted data, fall through to seeding.\n }\n }\n }\n\n if (!restored) {\n for (const [name, entry] of Object.entries(serviceEntries)) {\n const sa = serviceApps.get(name)!;\n const servicePrefix = joinPath(mountPath, name);\n const baseUrl = `${origin}${servicePrefix}`;\n sa.plugin.seed?.(sa.store, baseUrl);\n if (entry.seed && entry.emulator.seedFromConfig) {\n entry.emulator.seedFromConfig(sa.store, baseUrl, entry.seed, sa.webhooks);\n }\n }\n if (persistence) {\n enqueueSave(serviceApps);\n }\n }\n\n return serviceApps;\n }\n\n async function ensureInit(req: Request, pathSegments: string[]): Promise<Map<string, ServiceApp>> {\n if (apps) return apps;\n if (!initPromise) {\n const url = new URL(req.url);\n const origin = url.origin;\n mountPath = configuredMountPath ?? detectPrefix(req.url, pathSegments);\n initPromise = initApps(origin, mountPath).then((result) => {\n apps = result;\n });\n }\n await initPromise;\n return apps!;\n }\n\n return async function emulateNuxtHandler(event: NuxtEventLike): Promise<Response> {\n const req = requestFromEvent(event);\n const pathSegments = getPathSegments(event, paramName, configuredMountPath ?? undefined);\n\n if (pathSegments.length === 0) {\n return new Response(\"Not found\", { status: 404 });\n }\n\n const serviceApps = await ensureInit(req, pathSegments);\n\n const serviceName = pathSegments[0];\n const sa = serviceApps.get(serviceName);\n if (!sa) {\n return new Response(`Unknown service: ${serviceName}`, { status: 404 });\n }\n\n const restPath = \"/\" + pathSegments.slice(1).join(\"/\");\n const url = new URL(req.url);\n const strippedUrl = new URL(restPath + url.search, url.origin);\n\n const strippedReq = new Request(strippedUrl.toString(), {\n method: req.method,\n headers: req.headers,\n body: req.body,\n duplex: \"half\",\n } as RequestInit & { duplex: string });\n\n let response = await sa.app.fetch(strippedReq);\n\n const servicePrefix = joinPath(mountPath!, serviceName);\n response = await rewriteResponse(response, servicePrefix);\n\n if (persistence && MUTATING_METHODS.has(req.method)) {\n enqueueSave();\n }\n\n return response;\n };\n}\n\ninterface NitroInstanceLike {\n options?: { output?: { serverDir?: string } };\n}\n\n/**\n * Copy the `@emulators/core` UI fonts into the built server output.\n *\n * The emulator UI reads its fonts with `readFileSync(join(__dirname, \"fonts\", …))`.\n * In a Nitro build `__dirname` resolves to the server output root, so the font\n * files must exist at `<serverDir>/fonts/`. Nitro's tracing does not place them\n * there, so we copy them explicitly once the build is written.\n */\nfunction copyCoreFonts(nitro: NitroInstanceLike): void {\n const serverDir = nitro.options?.output?.serverDir;\n if (!serverDir) return;\n try {\n const require = createRequire(import.meta.url);\n const corePkg = require.resolve(\"@emulators/core/package.json\");\n const fontsDir = join(dirname(corePkg), \"dist\", \"fonts\");\n cpSync(fontsDir, join(serverDir, \"fonts\"), { recursive: true });\n } catch (err) {\n debug(\"nuxt\", \"font copy failed: %o\", err);\n }\n}\n\nexport function withEmulate<T>(nuxtConfig: T): T {\n const config = nuxtConfig as Record<string, unknown>;\n const nitro = { ...((config.nitro as Record<string, unknown> | undefined) ?? {}) };\n const existingHooks = (nitro.hooks as Record<string, unknown> | undefined) ?? {};\n const prevCompiled = existingHooks.compiled as ((nitro: NitroInstanceLike) => unknown) | undefined;\n\n const compiled = async (nitroInstance: NitroInstanceLike) => {\n if (prevCompiled) await prevCompiled(nitroInstance);\n copyCoreFonts(nitroInstance);\n };\n\n return {\n ...config,\n nitro: {\n ...nitro,\n hooks: { ...existingHooks, compiled },\n },\n } as T;\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AACvB,SAAS,SAAS,YAAY;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAoEP,IAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAEnE,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,QAAI,eAAe,iBAAiB,IAAI,IAAI,MAAM,GAAG;AACnD,kBAAY;AAAA,IACd;AAEA,WAAO;AAAA,EACT;AACF;AAcA,SAAS,cAAc,OAAgC;AACrD,QAAM,YAAY,MAAM,SAAS,QAAQ;AACzC,MAAI,CAAC,UAAW;AAChB,MAAI;AACF,UAAMC,WAAU,cAAc,YAAY,GAAG;AAC7C,UAAM,UAAUA,SAAQ,QAAQ,8BAA8B;AAC9D,UAAM,WAAW,KAAK,QAAQ,OAAO,GAAG,QAAQ,OAAO;AACvD,WAAO,UAAU,KAAK,WAAW,OAAO,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,EAChE,SAAS,KAAK;AACZ,UAAM,QAAQ,wBAAwB,GAAG;AAAA,EAC3C;AACF;AAEO,SAAS,YAAe,YAAkB;AAC/C,QAAM,SAAS;AACf,QAAM,QAAQ,EAAE,GAAK,OAAO,SAAiD,CAAC,EAAG;AACjF,QAAM,gBAAiB,MAAM,SAAiD,CAAC;AAC/E,QAAM,eAAe,cAAc;AAEnC,QAAM,WAAW,OAAO,kBAAqC;AAC3D,QAAI,aAAc,OAAM,aAAa,aAAa;AAClD,kBAAc,aAAa;AAAA,EAC7B;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,EAAE,GAAG,eAAe,SAAS;AAAA,IACtC;AAAA,EACF;AACF;","names":["headers","mountPath","require"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { cpSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport {\n createAdapterRuntime,\n debug,\n type AdapterEmulatorEntry,\n type AdapterEmulatorModule,\n type AdapterHandlerConfig,\n type GeneratedSecret,\n type PreparedServiceSeed,\n} from \"@emulators/core\";\nexport type { PersistenceAdapter } from \"@emulators/core\";\nexport type EmulatorModule = AdapterEmulatorModule;\nexport type EmulatorEntry = AdapterEmulatorEntry;\nexport type EmulateHandlerConfig = AdapterHandlerConfig;\nexport type { GeneratedSecret, PreparedServiceSeed };\nexport interface NuxtAdapterOptions {\n param?: string;\n routePrefix?: string;\n}\ntype HeaderValue = string | string[] | number | undefined;\ninterface NodeRequestLike {\n method?: string;\n url?: string;\n headers?: Record<string, HeaderValue>;\n}\nexport interface NuxtEventLike {\n req?: Request;\n node?: { req?: NodeRequestLike };\n context?: { params?: Record<string, unknown>; path?: string };\n}\nfunction normalizePrefix(prefix: string): string {\n return (prefix.startsWith(\"/\") ? prefix : `/${prefix}`).replace(/\\/+$/, \"\") || \"/\";\n}\nfunction joinPath(base: string, segment: string): string {\n return base === \"/\" ? `/${segment}` : `${base}/${segment}`;\n}\nfunction splitPath(path: string): string[] {\n return path.split(\"/\").filter(Boolean);\n}\nfunction getPathSegments(event: NuxtEventLike, param: string, routePrefix?: string): string[] {\n const params = event.context?.params ?? {};\n const value = params[param] ?? params._ ?? params.path;\n if (Array.isArray(value)) return value.flatMap((part) => splitPath(String(part)));\n if (typeof value === \"string\" && value) return splitPath(value);\n if (routePrefix && event.context?.path) {\n const path = event.context.path;\n return splitPath(path.startsWith(routePrefix) ? path.slice(routePrefix.length) : path);\n }\n return [];\n}\nfunction firstHeader(value: HeaderValue): string | undefined {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw === undefined ? undefined : String(raw).split(\",\")[0]?.trim();\n}\nfunction requestFromEvent(event: NuxtEventLike): Request {\n if (\n event.req &&\n typeof event.req.url === \"string\" &&\n typeof event.req.method === \"string\" &&\n typeof event.req.headers?.get === \"function\"\n ) {\n return event.req;\n }\n const nodeRequest = event.node?.req;\n if (!nodeRequest) throw new Error(\"Nuxt event must provide `req` or `node.req`\");\n const sourceHeaders = nodeRequest.headers ?? {};\n const protocol = firstHeader(sourceHeaders[\"x-forwarded-proto\"]) ?? \"http\";\n const host = firstHeader(sourceHeaders[\"x-forwarded-host\"]) ?? firstHeader(sourceHeaders.host) ?? \"localhost\";\n const headers = new Headers();\n for (const [name, value] of Object.entries(sourceHeaders)) {\n if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));\n else if (value !== undefined) headers.set(name, String(value));\n }\n const method = nodeRequest.method ?? \"GET\";\n const init: RequestInit & { duplex?: string } = { method, headers };\n if (method !== \"GET\" && method !== \"HEAD\") {\n init.body = nodeRequest as unknown as RequestInit[\"body\"];\n init.duplex = \"half\";\n }\n return new Request(new URL(nodeRequest.url ?? \"/\", `${protocol}://${host}`), init);\n}\nfunction detectPrefix(url: string, pathSegments: string[]): string {\n const pathname = new URL(url).pathname;\n const index = pathname.lastIndexOf(\"/\" + pathSegments.join(\"/\"));\n if (index >= 0) return pathname.slice(0, index) || \"/\";\n throw new Error(`Could not detect mount path from URL: ${url}`);\n}\nexport function createEmulateHandler(config: EmulateHandlerConfig, options: NuxtAdapterOptions = {}) {\n const param = options.param ?? \"path\";\n const configuredMountPath = options.routePrefix ? normalizePrefix(options.routePrefix) : null;\n const runtime = createAdapterRuntime(config, joinPath);\n let mountPath = configuredMountPath;\n const handler = async (event: NuxtEventLike): Promise<Response> => {\n const request = requestFromEvent(event);\n const path = getPathSegments(event, param, configuredMountPath ?? undefined);\n if (path.length === 0) return new Response(\"Not found\", { status: 404 });\n mountPath ??= detectPrefix(request.url, path);\n return runtime.handle(request, path, mountPath);\n };\n handler.generatedSecrets = runtime.generatedSecrets;\n return handler;\n}\ninterface NitroInstanceLike {\n options?: { output?: { serverDir?: string } };\n}\nfunction copyCoreFonts(nitro: NitroInstanceLike): void {\n const serverDir = nitro.options?.output?.serverDir;\n if (!serverDir) return;\n try {\n const corePackage = createRequire(import.meta.url).resolve(\"@emulators/core/package.json\");\n cpSync(join(dirname(corePackage), \"dist\", \"fonts\"), join(serverDir, \"fonts\"), { recursive: true });\n } catch (error) {\n debug(\"nuxt\", \"font copy failed: %o\", error);\n }\n}\nexport function withEmulate<T>(nuxtConfig: T): T {\n const config = nuxtConfig as Record<string, unknown>;\n const nitro = { ...((config.nitro as Record<string, unknown> | undefined) ?? {}) };\n const hooks = (nitro.hooks as Record<string, unknown> | undefined) ?? {};\n const previous = hooks.compiled as ((nitro: NitroInstanceLike) => unknown) | undefined;\n return {\n ...config,\n nitro: {\n ...nitro,\n hooks: {\n ...hooks,\n async compiled(instance: NitroInstanceLike) {\n if (previous) await previous(instance);\n copyCoreFonts(instance);\n },\n },\n },\n } as T;\n}\n"],"mappings":";AAAA,SAAS,cAAc;AACvB,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OAMK;AAqBP,SAAS,gBAAgB,QAAwB;AAC/C,UAAQ,OAAO,WAAW,GAAG,IAAI,SAAS,IAAI,MAAM,IAAI,QAAQ,QAAQ,EAAE,KAAK;AACjF;AACA,SAAS,SAAS,MAAc,SAAyB;AACvD,SAAO,SAAS,MAAM,IAAI,OAAO,KAAK,GAAG,IAAI,IAAI,OAAO;AAC1D;AACA,SAAS,UAAU,MAAwB;AACzC,SAAO,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AACvC;AACA,SAAS,gBAAgB,OAAsB,OAAe,aAAgC;AAC5F,QAAM,SAAS,MAAM,SAAS,UAAU,CAAC;AACzC,QAAM,QAAQ,OAAO,KAAK,KAAK,OAAO,KAAK,OAAO;AAClD,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,QAAQ,CAAC,SAAS,UAAU,OAAO,IAAI,CAAC,CAAC;AAChF,MAAI,OAAO,UAAU,YAAY,MAAO,QAAO,UAAU,KAAK;AAC9D,MAAI,eAAe,MAAM,SAAS,MAAM;AACtC,UAAM,OAAO,MAAM,QAAQ;AAC3B,WAAO,UAAU,KAAK,WAAW,WAAW,IAAI,KAAK,MAAM,YAAY,MAAM,IAAI,IAAI;AAAA,EACvF;AACA,SAAO,CAAC;AACV;AACA,SAAS,YAAY,OAAwC;AAC3D,QAAM,MAAM,MAAM,QAAQ,KAAK,IAAI,MAAM,CAAC,IAAI;AAC9C,SAAO,QAAQ,SAAY,S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AQ;AAAA,QACxB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emulators/adapter-nuxt",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -28,16 +28,19 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "@emulators/core": "0.10.0"
31
+ "@emulators/core": "0.11.1"
32
32
  },
33
33
  "devDependencies": {
34
34
  "tsup": "^8",
35
- "typescript": "^5.7"
35
+ "typescript": "^5.7",
36
+ "vitest": "^4.1.0",
37
+ "@emulators/github": "0.11.1"
36
38
  },
37
39
  "scripts": {
38
40
  "build": "tsup --clean",
39
41
  "dev": "tsup --watch",
40
42
  "clean": "rm -rf dist .turbo",
43
+ "test": "vitest run",
41
44
  "type-check": "tsc --noEmit",
42
45
  "lint": "eslint src"
43
46
  }