emulate 0.4.0 → 0.5.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 (50) hide show
  1. package/README.md +59 -10
  2. package/dist/api.d.ts +2 -1
  3. package/dist/api.js +232 -96
  4. package/dist/api.js.map +1 -1
  5. package/dist/{chunk-TEPNEZ63.js → chunk-AQ2CLRU3.js} +26 -23
  6. package/dist/chunk-AQ2CLRU3.js.map +1 -0
  7. package/dist/chunk-WVQMFHQM.js +83 -0
  8. package/dist/chunk-WVQMFHQM.js.map +1 -0
  9. package/dist/{dist-RDFBZ5O6.js → dist-4X2KPMAJ.js} +212 -47
  10. package/dist/dist-4X2KPMAJ.js.map +1 -0
  11. package/dist/{dist-OTJZRQ3Q.js → dist-5JVGPOL3.js} +217 -75
  12. package/dist/dist-5JVGPOL3.js.map +1 -0
  13. package/dist/{dist-G7WQPZ3Y.js → dist-CE6BUCWQ.js} +211 -60
  14. package/dist/dist-CE6BUCWQ.js.map +1 -0
  15. package/dist/{dist-6JFNJPUU.js → dist-CFST4X4K.js} +172 -22
  16. package/dist/dist-CFST4X4K.js.map +1 -0
  17. package/dist/{dist-YOVM5HEY.js → dist-ENKE2S7V.js} +521 -60
  18. package/dist/dist-ENKE2S7V.js.map +1 -0
  19. package/dist/{dist-RMK3BS5M.js → dist-ETHHYBGF.js} +197 -33
  20. package/dist/dist-ETHHYBGF.js.map +1 -0
  21. package/dist/{dist-QMOJM6DV.js → dist-IBXD3O6A.js} +239 -54
  22. package/dist/dist-IBXD3O6A.js.map +1 -0
  23. package/dist/dist-J6LHUR52.js +1899 -0
  24. package/dist/dist-J6LHUR52.js.map +1 -0
  25. package/dist/{dist-6EW7SSOZ.js → dist-KKTYBE5S.js} +391 -222
  26. package/dist/dist-KKTYBE5S.js.map +1 -0
  27. package/dist/{dist-VVXVP5EZ.js → dist-LDUHEJAN.js} +553 -91
  28. package/dist/dist-LDUHEJAN.js.map +1 -0
  29. package/dist/{dist-B674PYKV.js → dist-PWGOAQC6.js} +22 -43
  30. package/dist/dist-PWGOAQC6.js.map +1 -0
  31. package/dist/{dist-H6JYGQM4.js → dist-REDHDZ3V.js} +272 -157
  32. package/dist/dist-REDHDZ3V.js.map +1 -0
  33. package/dist/fonts/favicon.ico +0 -0
  34. package/dist/helpers-LXLP3DFE-LBOTATT5.js +17 -0
  35. package/dist/helpers-LXLP3DFE-LBOTATT5.js.map +1 -0
  36. package/dist/index.js +365 -108
  37. package/dist/index.js.map +1 -1
  38. package/package.json +17 -14
  39. package/dist/chunk-TEPNEZ63.js.map +0 -1
  40. package/dist/dist-6EW7SSOZ.js.map +0 -1
  41. package/dist/dist-6JFNJPUU.js.map +0 -1
  42. package/dist/dist-B674PYKV.js.map +0 -1
  43. package/dist/dist-G7WQPZ3Y.js.map +0 -1
  44. package/dist/dist-H6JYGQM4.js.map +0 -1
  45. package/dist/dist-OTJZRQ3Q.js.map +0 -1
  46. package/dist/dist-QMOJM6DV.js.map +0 -1
  47. package/dist/dist-RDFBZ5O6.js.map +0 -1
  48. package/dist/dist-RMK3BS5M.js.map +0 -1
  49. package/dist/dist-VVXVP5EZ.js.map +0 -1
  50. package/dist/dist-YOVM5HEY.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../@emulators/stripe/src/store.ts","../../@emulators/stripe/src/helpers.ts","../../@emulators/stripe/src/formatters.ts","../../@emulators/stripe/src/routes/customers.ts","../../@emulators/stripe/src/routes/payment-intents.ts","../../@emulators/stripe/src/routes/payment-methods.ts","../../@emulators/stripe/src/routes/charges.ts","../../@emulators/stripe/src/routes/products.ts","../../@emulators/stripe/src/routes/prices.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../../@emulators/stripe/src/routes/checkout-sessions.ts","../../@emulators/stripe/src/routes/customer-sessions.ts","../../@emulators/stripe/src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type {\n StripeCustomer,\n StripeProduct,\n StripePrice,\n StripePaymentIntent,\n StripeCharge,\n StripeCheckoutSession,\n} from \"./entities.js\";\n\nexport interface StripeStore {\n customers: Collection<StripeCustomer>;\n products: Collection<StripeProduct>;\n prices: Collection<StripePrice>;\n paymentIntents: Collection<StripePaymentIntent>;\n charges: Collection<StripeCharge>;\n checkoutSessions: Collection<StripeCheckoutSession>;\n}\n\nexport function getStripeStore(store: Store): StripeStore {\n return {\n customers: store.collection<StripeCustomer>(\"stripe.customers\", [\"stripe_id\", \"email\"]),\n products: store.collection<StripeProduct>(\"stripe.products\", [\"stripe_id\"]),\n prices: store.collection<StripePrice>(\"stripe.prices\", [\"stripe_id\", \"product_id\"]),\n paymentIntents: store.collection<StripePaymentIntent>(\"stripe.payment_intents\", [\"stripe_id\", \"customer_id\"]),\n charges: store.collection<StripeCharge>(\"stripe.charges\", [\"stripe_id\", \"customer_id\", \"payment_intent_id\"]),\n checkoutSessions: store.collection<StripeCheckoutSession>(\"stripe.checkout_sessions\", [\"stripe_id\", \"customer_id\"]),\n };\n}\n","import { randomBytes } from \"crypto\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport type { Entity, Collection } from \"@emulators/core\";\n\nconst NUMERIC_KEYS = new Set([\n \"amount\",\n \"unit_amount\",\n \"quantity\",\n \"amount_total\",\n \"amount_subtotal\",\n \"application_fee_amount\",\n \"transfer_amount\",\n]);\n\nexport function stripeId(prefix: string): string {\n return `${prefix}_${randomBytes(12).toString(\"base64url\").slice(0, 24)}`;\n}\n\nexport function toUnixTimestamp(iso: string): number {\n return Math.floor(new Date(iso).getTime() / 1000);\n}\n\n/**\n * Parse request body from either JSON or form-urlencoded format.\n * Stripe's SDK sends application/x-www-form-urlencoded by default,\n * but JSON is also common from direct API calls.\n */\nexport async function parseStripeBody(c: Context): Promise<Record<string, unknown>> {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n\n if (!rawText) return {};\n\n if (contentType.includes(\"application/json\")) {\n try {\n const parsed = JSON.parse(rawText);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : {};\n } catch {\n return {};\n }\n }\n\n const params = new URLSearchParams(rawText);\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of params) {\n if (key.includes(\"[\")) {\n const parts = key.replace(/]/g, \"\").split(\"[\");\n let target: Record<string, unknown> | unknown[] = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const nextIsIndex = /^\\d+$/.test(parts[i + 1]);\n const current = (target as Record<string, unknown>)[part];\n if (current === undefined || current === null || typeof current !== \"object\") {\n (target as Record<string, unknown>)[part] = nextIsIndex ? [] : {};\n }\n target = (target as Record<string, unknown>)[part] as Record<string, unknown> | unknown[];\n }\n const lastKey = parts[parts.length - 1];\n const num = Number(value);\n const coerced = NUMERIC_KEYS.has(lastKey) && Number.isFinite(num) ? num : value;\n if (Array.isArray(target)) {\n const idx = lastKey === \"\" ? target.length : parseInt(lastKey, 10);\n target[idx] = coerced;\n } else {\n (target as Record<string, unknown>)[lastKey] = coerced;\n }\n } else {\n const num = Number(value);\n result[key] = NUMERIC_KEYS.has(key) && Number.isFinite(num) ? num : value;\n }\n }\n\n return result;\n}\n\n/**\n * Return a Stripe-format error response.\n * Stripe errors use { error: { type, message, code?, param? } }\n */\nexport function stripeError(\n c: Context,\n status: number,\n type: \"invalid_request_error\" | \"card_error\" | \"api_error\",\n message: string,\n code?: string,\n param?: string,\n) {\n return c.json(\n {\n error: {\n type,\n message,\n ...(code && { code }),\n ...(param && { param }),\n },\n },\n status as ContentfulStatusCode,\n );\n}\n\n/**\n * Stripe-style cursor-based list pagination.\n * Supports starting_after, ending_before, limit, and created[gte]/created[lte] filtering.\n */\nexport function stripeList<T extends Entity & { stripe_id: string; created_at: string }>(\n c: Context,\n items: T[],\n url: string,\n formatFn: (item: T) => Record<string, unknown>,\n) {\n const limit = Math.min(parseInt(c.req.query(\"limit\") ?? \"10\", 10), 100);\n const startingAfter = c.req.query(\"starting_after\");\n const endingBefore = c.req.query(\"ending_before\");\n const createdGte = c.req.query(\"created[gte]\");\n const createdLte = c.req.query(\"created[lte]\");\n\n let filtered = items;\n\n // Date range filtering\n if (createdGte) {\n const gte = parseInt(createdGte, 10);\n filtered = filtered.filter((item) => toUnixTimestamp(item.created_at) >= gte);\n }\n if (createdLte) {\n const lte = parseInt(createdLte, 10);\n filtered = filtered.filter((item) => toUnixTimestamp(item.created_at) <= lte);\n }\n\n // Sort newest first (Stripe default)\n filtered.sort((a, b) => b.id - a.id);\n\n // Cursor-based pagination\n if (startingAfter) {\n const idx = filtered.findIndex((item) => item.stripe_id === startingAfter);\n if (idx !== -1) {\n filtered = filtered.slice(idx + 1);\n }\n } else if (endingBefore) {\n const idx = filtered.findIndex((item) => item.stripe_id === endingBefore);\n if (idx !== -1) {\n filtered = filtered.slice(0, idx);\n filtered = filtered.slice(-limit);\n }\n }\n\n const page = filtered.slice(0, limit);\n const hasMore = filtered.length > limit;\n\n return c.json({\n object: \"list\",\n url,\n has_more: hasMore,\n data: page.map(formatFn),\n });\n}\n\n/**\n * Apply Stripe's expand[] parameter to embed related objects.\n * Replaces ID strings with full formatted objects.\n */\nexport function applyExpand(\n obj: Record<string, unknown>,\n expandPaths: string[],\n resolvers: Record<string, (id: string) => Record<string, unknown> | undefined>,\n): Record<string, unknown> {\n if (!expandPaths || expandPaths.length === 0) return obj;\n\n const result = { ...obj };\n for (const path of expandPaths) {\n const resolver = resolvers[path];\n const id = result[path];\n if (resolver && typeof id === \"string\") {\n const expanded = resolver(id);\n if (expanded) {\n result[path] = expanded;\n }\n }\n }\n return result;\n}\n\n/**\n * Parse expand[] from query params or body.\n */\nexport function parseExpand(c: Context): string[] {\n const fromQuery = c.req.queries(\"expand[]\") ?? [];\n return fromQuery;\n}\n","import { toUnixTimestamp } from \"./helpers.js\";\nimport type { StripeCustomer, StripePaymentIntent } from \"./entities.js\";\n\nexport function formatCustomer(c: StripeCustomer) {\n return {\n id: c.stripe_id,\n object: \"customer\" as const,\n email: c.email,\n name: c.name,\n description: c.description,\n metadata: c.metadata,\n created: toUnixTimestamp(c.created_at),\n livemode: false,\n };\n}\n\nexport function formatPaymentIntent(pi: StripePaymentIntent) {\n return {\n id: pi.stripe_id,\n object: \"payment_intent\" as const,\n amount: pi.amount,\n currency: pi.currency,\n status: pi.status,\n customer: pi.customer_id,\n description: pi.description,\n payment_method: pi.payment_method,\n metadata: pi.metadata,\n created: toUnixTimestamp(pi.created_at),\n livemode: false,\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { stripeId, parseStripeBody, stripeError, stripeList } from \"../helpers.js\";\nimport { formatCustomer } from \"../formatters.js\";\n\nexport function customerRoutes({ app, store, webhooks }: RouteContext): void {\n const ss = getStripeStore(store);\n\n app.post(\"/v1/customers\", async (c) => {\n const body = await parseStripeBody(c);\n const customer = ss.customers.insert({\n stripe_id: stripeId(\"cus\"),\n email: (body.email as string) ?? null,\n name: (body.name as string) ?? null,\n description: (body.description as string) ?? null,\n metadata: (body.metadata as Record<string, string>) ?? {},\n });\n\n await webhooks.dispatch(\n \"customer.created\",\n undefined,\n { type: \"customer.created\", data: { object: formatCustomer(customer) } },\n \"stripe\",\n );\n\n return c.json(formatCustomer(customer), 200);\n });\n\n app.get(\"/v1/customers/:id\", (c) => {\n const customer = ss.customers.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!customer)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such customer: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n return c.json(formatCustomer(customer));\n });\n\n app.post(\"/v1/customers/:id\", async (c) => {\n const customer = ss.customers.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!customer)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such customer: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n const body = await parseStripeBody(c);\n const updated = ss.customers.update(customer.id, {\n ...(body.email !== undefined && { email: body.email as string }),\n ...(body.name !== undefined && { name: body.name as string }),\n ...(body.description !== undefined && { description: body.description as string }),\n ...(body.metadata !== undefined && { metadata: body.metadata as Record<string, string> }),\n });\n\n await webhooks.dispatch(\n \"customer.updated\",\n undefined,\n { type: \"customer.updated\", data: { object: formatCustomer(updated!) } },\n \"stripe\",\n );\n\n return c.json(formatCustomer(updated!));\n });\n\n app.delete(\"/v1/customers/:id\", async (c) => {\n const customer = ss.customers.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!customer)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such customer: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n\n // Cascade: nullify customer_id on related entities\n for (const pi of ss.paymentIntents.findBy(\"customer_id\", customer.stripe_id)) {\n ss.paymentIntents.update(pi.id, { customer_id: null });\n }\n for (const ch of ss.charges.findBy(\"customer_id\", customer.stripe_id)) {\n ss.charges.update(ch.id, { customer_id: null });\n }\n for (const cs of ss.checkoutSessions.findBy(\"customer_id\", customer.stripe_id)) {\n ss.checkoutSessions.update(cs.id, { customer_id: null });\n }\n\n ss.customers.delete(customer.id);\n\n await webhooks.dispatch(\n \"customer.deleted\",\n undefined,\n { type: \"customer.deleted\", data: { object: { ...formatCustomer(customer), deleted: true } } },\n \"stripe\",\n );\n\n return c.json({ id: customer.stripe_id, object: \"customer\", deleted: true });\n });\n\n app.get(\"/v1/customers\", (c) => {\n let items = ss.customers.all();\n const email = c.req.query(\"email\");\n if (email) items = items.filter((cust) => cust.email === email);\n return stripeList(c, items, \"/v1/customers\", formatCustomer);\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { stripeId, parseStripeBody, stripeError, stripeList, applyExpand, parseExpand } from \"../helpers.js\";\nimport { formatCustomer, formatPaymentIntent } from \"../formatters.js\";\nimport type { StripePaymentIntent, PaymentIntentStatus } from \"../entities.js\";\n\nexport function paymentIntentRoutes({ app, store, webhooks }: RouteContext): void {\n const ss = getStripeStore(store);\n\n const expandResolvers = {\n customer: (id: string) => {\n const cust = ss.customers.findOneBy(\"stripe_id\", id);\n return cust ? formatCustomer(cust) : undefined;\n },\n };\n\n app.post(\"/v1/payment_intents\", async (c) => {\n const body = await parseStripeBody(c);\n if (!body.amount || !body.currency) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n \"Missing required param: amount and currency are required.\",\n undefined,\n \"amount\",\n );\n }\n\n if (body.customer && !ss.customers.findOneBy(\"stripe_id\", body.customer as string)) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such customer: '${body.customer}'`,\n \"resource_missing\",\n \"customer\",\n );\n }\n\n const status: PaymentIntentStatus = body.payment_method ? \"requires_confirmation\" : \"requires_payment_method\";\n\n const pi = ss.paymentIntents.insert({\n stripe_id: stripeId(\"pi\"),\n amount: body.amount as number,\n currency: (body.currency as string).toLowerCase(),\n status,\n customer_id: (body.customer as string) ?? null,\n description: (body.description as string) ?? null,\n payment_method: (body.payment_method as string) ?? null,\n metadata: (body.metadata as Record<string, string>) ?? {},\n });\n\n await webhooks.dispatch(\n \"payment_intent.created\",\n undefined,\n { type: \"payment_intent.created\", data: { object: formatPaymentIntent(pi) } },\n \"stripe\",\n );\n\n return c.json(formatPaymentIntent(pi), 200);\n });\n\n app.get(\"/v1/payment_intents/:id\", (c) => {\n const pi = ss.paymentIntents.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!pi)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such payment_intent: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n const expand = parseExpand(c);\n const result = applyExpand(formatPaymentIntent(pi), expand, expandResolvers);\n return c.json(result);\n });\n\n app.post(\"/v1/payment_intents/:id\", async (c) => {\n const pi = ss.paymentIntents.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!pi)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such payment_intent: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n const body = await parseStripeBody(c);\n\n const updates: Partial<StripePaymentIntent> = {};\n if (body.amount !== undefined) updates.amount = body.amount as number;\n if (body.currency !== undefined) updates.currency = (body.currency as string).toLowerCase();\n if (body.description !== undefined) updates.description = body.description as string;\n if (body.metadata !== undefined) updates.metadata = body.metadata as Record<string, string>;\n if (body.payment_method !== undefined) {\n updates.payment_method = body.payment_method as string;\n if (pi.status === \"requires_payment_method\") {\n updates.status = \"requires_confirmation\";\n }\n }\n\n const updated = ss.paymentIntents.update(pi.id, updates);\n return c.json(formatPaymentIntent(updated!));\n });\n\n app.post(\"/v1/payment_intents/:id/confirm\", async (c) => {\n const pi = ss.paymentIntents.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!pi)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such payment_intent: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n const body = await parseStripeBody(c);\n\n if (pi.status !== \"requires_confirmation\" && pi.status !== \"requires_payment_method\") {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `This PaymentIntent's status is ${pi.status}, which does not allow confirmation.`,\n \"payment_intent_unexpected_state\",\n );\n }\n\n if (body.payment_method) {\n ss.paymentIntents.update(pi.id, { payment_method: body.payment_method as string });\n }\n\n const updated = ss.paymentIntents.update(pi.id, { status: \"succeeded\" })!;\n\n const charge = ss.charges.insert({\n stripe_id: stripeId(\"ch\"),\n amount: updated.amount,\n currency: updated.currency,\n status: \"succeeded\",\n customer_id: updated.customer_id,\n payment_intent_id: updated.stripe_id,\n description: updated.description,\n metadata: updated.metadata,\n });\n\n await webhooks.dispatch(\n \"payment_intent.succeeded\",\n undefined,\n { type: \"payment_intent.succeeded\", data: { object: formatPaymentIntent(updated) } },\n \"stripe\",\n );\n\n await webhooks.dispatch(\n \"charge.succeeded\",\n undefined,\n {\n type: \"charge.succeeded\",\n data: {\n object: {\n id: charge.stripe_id,\n object: \"charge\",\n amount: charge.amount,\n currency: charge.currency,\n status: charge.status,\n },\n },\n },\n \"stripe\",\n );\n\n return c.json(formatPaymentIntent(updated));\n });\n\n app.post(\"/v1/payment_intents/:id/cancel\", async (c) => {\n const pi = ss.paymentIntents.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!pi)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such payment_intent: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n\n if (pi.status === \"succeeded\" || pi.status === \"canceled\") {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `This PaymentIntent's status is ${pi.status}, which does not allow cancellation.`,\n \"payment_intent_unexpected_state\",\n );\n }\n\n const updated = ss.paymentIntents.update(pi.id, { status: \"canceled\" })!;\n\n await webhooks.dispatch(\n \"payment_intent.canceled\",\n undefined,\n { type: \"payment_intent.canceled\", data: { object: formatPaymentIntent(updated) } },\n \"stripe\",\n );\n\n return c.json(formatPaymentIntent(updated));\n });\n\n app.get(\"/v1/payment_intents\", (c) => {\n let items = ss.paymentIntents.all();\n const customerId = c.req.query(\"customer\");\n const status = c.req.query(\"status\");\n if (customerId) items = items.filter((pi) => pi.customer_id === customerId);\n if (status) items = items.filter((pi) => pi.status === status);\n return stripeList(c, items, \"/v1/payment_intents\", formatPaymentIntent);\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { stripeError } from \"../helpers.js\";\nimport { getStripeStore } from \"../store.js\";\n\nexport function paymentMethodRoutes({ app, store }: RouteContext): void {\n const ss = getStripeStore(store);\n\n app.get(\"/v1/payment_methods\", (c) => {\n const customerId = c.req.query(\"customer\");\n if (customerId && !ss.customers.findOneBy(\"stripe_id\", customerId)) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such customer: '${customerId}'`,\n \"resource_missing\",\n \"customer\",\n );\n }\n\n return c.json(\n {\n object: \"list\" as const,\n url: \"/v1/payment_methods\",\n has_more: false,\n data: [],\n },\n 200,\n );\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { toUnixTimestamp, stripeError, stripeList, applyExpand, parseExpand } from \"../helpers.js\";\nimport { formatCustomer, formatPaymentIntent } from \"../formatters.js\";\nimport type { StripeCharge } from \"../entities.js\";\n\nfunction formatCharge(ch: StripeCharge) {\n return {\n id: ch.stripe_id,\n object: \"charge\" as const,\n amount: ch.amount,\n currency: ch.currency,\n status: ch.status,\n customer: ch.customer_id,\n payment_intent: ch.payment_intent_id,\n description: ch.description,\n metadata: ch.metadata,\n created: toUnixTimestamp(ch.created_at),\n livemode: false,\n };\n}\n\nexport function chargeRoutes({ app, store }: RouteContext): void {\n const ss = getStripeStore(store);\n\n const expandResolvers = {\n customer: (id: string) => {\n const cust = ss.customers.findOneBy(\"stripe_id\", id);\n return cust ? formatCustomer(cust) : undefined;\n },\n payment_intent: (id: string) => {\n const pi = ss.paymentIntents.findOneBy(\"stripe_id\", id);\n return pi ? formatPaymentIntent(pi) : undefined;\n },\n };\n\n app.get(\"/v1/charges/:id\", (c) => {\n const charge = ss.charges.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!charge)\n return stripeError(c, 404, \"invalid_request_error\", `No such charge: '${c.req.param(\"id\")}'`, \"resource_missing\");\n const expand = parseExpand(c);\n const result = applyExpand(formatCharge(charge), expand, expandResolvers);\n return c.json(result);\n });\n\n app.get(\"/v1/charges\", (c) => {\n let items = ss.charges.all();\n const customerId = c.req.query(\"customer\");\n const piId = c.req.query(\"payment_intent\");\n if (customerId) items = items.filter((ch) => ch.customer_id === customerId);\n if (piId) items = items.filter((ch) => ch.payment_intent_id === piId);\n return stripeList(c, items, \"/v1/charges\", formatCharge);\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { stripeId, toUnixTimestamp, parseStripeBody, stripeError, stripeList } from \"../helpers.js\";\nimport type { StripeProduct } from \"../entities.js\";\n\nfunction formatProduct(p: StripeProduct) {\n return {\n id: p.stripe_id,\n object: \"product\",\n name: p.name,\n description: p.description,\n active: p.active,\n metadata: p.metadata,\n created: toUnixTimestamp(p.created_at),\n livemode: false,\n };\n}\n\nexport function productRoutes({ app, store, webhooks }: RouteContext): void {\n const ss = getStripeStore(store);\n\n app.post(\"/v1/products\", async (c) => {\n const body = await parseStripeBody(c);\n if (!body.name)\n return stripeError(c, 400, \"invalid_request_error\", \"Missing required param: name.\", undefined, \"name\");\n const product = ss.products.insert({\n stripe_id: stripeId(\"prod\"),\n name: body.name as string,\n description: (body.description as string) ?? null,\n active: (body.active as boolean) ?? true,\n metadata: (body.metadata as Record<string, string>) ?? {},\n });\n\n await webhooks.dispatch(\n \"product.created\",\n undefined,\n { type: \"product.created\", data: { object: formatProduct(product) } },\n \"stripe\",\n );\n\n return c.json(formatProduct(product), 200);\n });\n\n app.get(\"/v1/products/:id\", (c) => {\n const product = ss.products.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!product)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such product: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n return c.json(formatProduct(product));\n });\n\n app.get(\"/v1/products\", (c) => {\n let items = ss.products.all();\n const active = c.req.query(\"active\");\n if (active !== undefined) items = items.filter((p) => p.active === (active === \"true\"));\n return stripeList(c, items, \"/v1/products\", formatProduct);\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport {\n stripeId,\n toUnixTimestamp,\n parseStripeBody,\n stripeError,\n stripeList,\n applyExpand,\n parseExpand,\n} from \"../helpers.js\";\nimport type { StripePrice, StripeProduct } from \"../entities.js\";\n\nfunction formatPrice(p: StripePrice) {\n return {\n id: p.stripe_id,\n object: \"price\",\n product: p.product_id,\n currency: p.currency,\n unit_amount: p.unit_amount,\n type: p.type,\n active: p.active,\n metadata: p.metadata,\n created: toUnixTimestamp(p.created_at),\n livemode: false,\n };\n}\n\nfunction formatProduct(p: StripeProduct) {\n return {\n id: p.stripe_id,\n object: \"product\",\n name: p.name,\n active: p.active,\n created: toUnixTimestamp(p.created_at),\n livemode: false,\n };\n}\n\nexport function priceRoutes({ app, store, webhooks }: RouteContext): void {\n const ss = getStripeStore(store);\n\n const expandResolvers = {\n product: (id: string) => {\n const prod = ss.products.findOneBy(\"stripe_id\", id);\n return prod ? formatProduct(prod) : undefined;\n },\n };\n\n app.post(\"/v1/prices\", async (c) => {\n const body = await parseStripeBody(c);\n if (!body.currency || !body.product) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n \"Missing required param: currency and product are required.\",\n undefined,\n \"currency\",\n );\n }\n if (!ss.products.findOneBy(\"stripe_id\", body.product as string)) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such product: '${body.product}'`,\n \"resource_missing\",\n \"product\",\n );\n }\n const price = ss.prices.insert({\n stripe_id: stripeId(\"price\"),\n product_id: body.product as string,\n currency: (body.currency as string).toLowerCase(),\n unit_amount: (body.unit_amount as number) ?? null,\n type: body.recurring ? \"recurring\" : \"one_time\",\n active: (body.active as boolean) ?? true,\n metadata: (body.metadata as Record<string, string>) ?? {},\n });\n\n await webhooks.dispatch(\n \"price.created\",\n undefined,\n { type: \"price.created\", data: { object: formatPrice(price) } },\n \"stripe\",\n );\n\n return c.json(formatPrice(price), 200);\n });\n\n app.get(\"/v1/prices/:id\", (c) => {\n const price = ss.prices.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!price)\n return stripeError(c, 404, \"invalid_request_error\", `No such price: '${c.req.param(\"id\")}'`, \"resource_missing\");\n const expand = parseExpand(c);\n const result = applyExpand(formatPrice(price), expand, expandResolvers);\n return c.json(result);\n });\n\n app.get(\"/v1/prices\", (c) => {\n let items = ss.prices.all();\n const productId = c.req.query(\"product\");\n const active = c.req.query(\"active\");\n if (productId) items = items.filter((p) => p.product_id === productId);\n if (active !== undefined) items = items.filter((p) => p.active === (active === \"true\"));\n return stripeList(c, items, \"/v1/prices\", formatPrice);\n });\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids)\n .map((id) => this.items.get(id)!)\n .filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`,\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport {\n authMiddleware,\n type AuthFallback,\n type TokenMap,\n type AppKeyResolver,\n type AppEnv,\n} from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://emulate.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403,\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404,\n ),\n );\n\n return { app, store, webhooks, port, baseUrl, tokenMap };\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>,\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return event === \"ping\" || s.events.includes(\"*\") || s.events.includes(event);\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode,\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"hono\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString());\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n","const isDebug =\n typeof process !== \"undefined\" &&\n (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nconst FAVICON = readFileSync(join(__dirname, \"fonts\", \"favicon.ico\"));\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[name];\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n\n app.get(\"/_emulate/favicon.ico\", (c) => {\n return new Response(FAVICON, {\n headers: {\n \"Content-Type\": \"image/x-icon\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n });\n });\n}\n","import type { Context } from \"hono\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(c: Context, totalCount: number, page: number, perPage: number): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","export function escapeHtml(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n\n.inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}\n.inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}\n.inspector-tabs a{\n padding:7px 16px;border-radius:6px;text-decoration:none;\n font-size:.8125rem;color:#1a8c00;border:1px solid transparent;\n transition:color .15s,border-color .15s;\n}\n.inspector-tabs a:hover{color:#33ff00;}\n.inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}\n.inspector-section{margin-bottom:24px;}\n.inspector-section h2{\n font-family:'Geist Pixel',monospace;\n font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;\n}\n.inspector-section h3{\n font-family:'Geist Pixel',monospace;\n font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;\n}\n.inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}\n.inspector-table th,.inspector-table td{\n text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;\n font-size:.8125rem;\n}\n.inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}\n.inspector-table td{color:#33ff00;}\n.inspector-table tbody tr{transition:background .1s;}\n.inspector-table tbody tr:hover{background:#0a3300;}\n.inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}\n\n.checkout-layout{\n display:flex;min-height:calc(100vh - 42px);\n}\n.checkout-summary{\n flex:1;background:#020;padding:48px 40px 48px 10%;\n display:flex;flex-direction:column;justify-content:center;\n border-right:1px solid #0a3300;\n}\n.checkout-form-side{\n flex:1;background:#000;padding:48px 10% 48px 40px;\n display:flex;flex-direction:column;justify-content:center;\n}\n.checkout-merchant{\n display:flex;align-items:center;gap:10px;margin-bottom:6px;\n}\n.checkout-merchant-name{\n font-family:'Geist Pixel',monospace;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-test-badge{\n font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;\n}\n.checkout-total{\n font-family:'Geist Pixel',monospace;\n font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;\n}\n.checkout-line-item{\n display:flex;align-items:center;gap:14px;padding:14px 0;\n border-bottom:1px solid #0a3300;\n}\n.checkout-line-item:first-child{border-top:1px solid #0a3300;}\n.checkout-item-icon{\n width:42px;height:42px;border-radius:6px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;\n}\n.checkout-item-details{flex:1;min-width:0;}\n.checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}\n.checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.checkout-item-price{\n font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;\n}\n.checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}\n.checkout-totals{margin-top:20px;}\n.checkout-totals-row{\n display:flex;justify-content:space-between;padding:6px 0;\n font-size:.8125rem;color:#1a8c00;\n}\n.checkout-totals-row.total{\n border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-form-section{margin-bottom:24px;}\n.checkout-form-label{\n font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;\n}\n.checkout-input{\n width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;\n background:#020;color:#33ff00;font:inherit;font-size:.875rem;\n transition:border-color .15s;outline:none;\n}\n.checkout-input:focus{border-color:#33ff00;}\n.checkout-input::placeholder{color:#116600;}\n.checkout-card-box{\n border:1px solid #0a3300;border-radius:6px;padding:14px;\n background:#020;\n}\n.checkout-card-row{\n display:flex;gap:12px;margin-top:10px;\n}\n.checkout-card-row .checkout-input{flex:1;}\n.checkout-sim-note{\n font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;\n font-style:italic;\n}\n.checkout-pay-btn{\n width:100%;padding:14px;border:none;border-radius:8px;\n background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;\n cursor:pointer;transition:background .15s;\n font-family:'Geist Pixel',monospace;\n}\n.checkout-pay-btn:hover{background:#44ff22;}\n.checkout-cancel{\n text-align:center;margin-top:14px;\n}\n.checkout-cancel a{\n color:#1a8c00;text-decoration:none;font-size:.8125rem;\n transition:color .15s;\n}\n.checkout-cancel a:hover{color:#33ff00;}\n@media(max-width:768px){\n .checkout-layout{flex-direction:column;}\n .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}\n .checkout-form-side{padding:32px 20px;}\n}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<link rel=\"icon\" href=\"/_emulate/favicon.ico\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(title: string, subtitle: string, body: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(title: string, sidebarHtml: string, bodyHtml: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface InspectorTab {\n id: string;\n label: string;\n href: string;\n}\n\nexport function renderInspectorPage(\n title: string,\n tabs: InspectorTab[],\n activeTab: string,\n body: string,\n service?: string,\n): string {\n const tabLinks = tabs\n .map(\n (t) => `<a href=\"${escapeAttr(t.href)}\" class=\"${t.id === activeTab ? \"active\" : \"\"}\">${escapeHtml(t.label)}</a>`,\n )\n .join(\"\");\n\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"inspector-layout\">\n <nav class=\"inspector-tabs\">${tabLinks}</nav>\n ${body}\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderFormPostPage(action: string, fields: Record<string, string>, service?: string): string {\n const hiddens = Object.entries(fields)\n .filter(([, v]) => v != null)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\\n\");\n\n return `${head(\"Redirecting\")}\n<body onload=\"document.forms[0].submit()\">\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\" style=\"text-align:center\">\n <div class=\"card-subtitle\">Redirecting&hellip;</div>\n <form method=\"POST\" action=\"${escapeAttr(action)}\">\n${hiddens}\n <noscript><button type=\"submit\" class=\"user-btn\" style=\"margin-top:12px;justify-content:center\">\n <span class=\"user-login\">Continue</span>\n </button></noscript>\n </form>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface CheckoutLineItem {\n name: string;\n quantity: number;\n unitPrice: number;\n totalPrice: number;\n currency: string;\n}\n\nexport interface CheckoutPageOptions {\n merchantName?: string;\n lineItems: CheckoutLineItem[];\n subtotal: number;\n total: number;\n currency: string;\n sessionId: string;\n cancelUrl?: string | null;\n}\n\nexport function renderCheckoutPage(opts: CheckoutPageOptions, service?: string): string {\n const fmt = (cents: number, cur: string) => `$${(cents / 100).toFixed(2)} ${cur.toUpperCase()}`;\n const fmtShort = (cents: number) => `$${(cents / 100).toFixed(2)}`;\n\n const itemsHtml =\n opts.lineItems.length > 0\n ? opts.lineItems\n .map((li) => {\n const initial = li.name.charAt(0).toUpperCase();\n const unitNote =\n li.quantity > 1 ? `<div class=\"checkout-item-unit\">${fmtShort(li.unitPrice)} each</div>` : \"\";\n return `<div class=\"checkout-line-item\">\n <div class=\"checkout-item-icon\">${escapeHtml(initial)}</div>\n <div class=\"checkout-item-details\">\n <div class=\"checkout-item-name\">${escapeHtml(li.name)}</div>\n <div class=\"checkout-item-qty\">Qty ${li.quantity}</div>\n </div>\n <div>\n <div class=\"checkout-item-price\">${fmtShort(li.totalPrice)}</div>\n ${unitNote}\n </div>\n</div>`;\n })\n .join(\"\")\n : '<p class=\"empty\">No line items</p>';\n\n const totalsHtml = `<div class=\"checkout-totals\">\n <div class=\"checkout-totals-row\">\n <span>Subtotal</span><span>${fmtShort(opts.subtotal)}</span>\n </div>\n <div class=\"checkout-totals-row total\">\n <span>Total due</span><span>${fmt(opts.total, opts.currency)}</span>\n </div>\n</div>`;\n\n const cancelHtml = opts.cancelUrl\n ? `<div class=\"checkout-cancel\"><a href=\"${escapeAttr(opts.cancelUrl)}\">Cancel</a></div>`\n : \"\";\n\n const merchant = opts.merchantName ? escapeHtml(opts.merchantName) : \"Checkout\";\n\n return `${head(\"Checkout\")}\n<body>\n${emuBar(service)}\n<div class=\"checkout-layout\">\n <div class=\"checkout-summary\">\n <div class=\"checkout-merchant\">\n <span class=\"checkout-merchant-name\">${merchant}</span>\n <span class=\"checkout-test-badge\">Test Mode</span>\n </div>\n <div class=\"checkout-total\">${fmtShort(opts.total)}</div>\n ${itemsHtml}\n ${totalsHtml}\n </div>\n <div class=\"checkout-form-side\">\n <form method=\"post\" action=\"/checkout/${escapeAttr(opts.sessionId)}/complete\">\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Email</label>\n <input type=\"email\" name=\"email\" class=\"checkout-input\" placeholder=\"you@example.com\"/>\n </div>\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Card information</label>\n <div class=\"checkout-card-box\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"1234 1234 1234 1234\" disabled/>\n <div class=\"checkout-card-row\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"MM / YY\" disabled/>\n <input type=\"text\" class=\"checkout-input\" placeholder=\"CVC\" disabled/>\n </div>\n </div>\n <div class=\"checkout-sim-note\">Card fields are simulated. Payment will be auto-approved.</div>\n </div>\n <button type=\"submit\" class=\"checkout-pay-btn\">Pay ${fmtShort(opts.total)}</button>\n </form>\n ${cancelHtml}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>` : \"\";\n const emailLine = opts.email ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>` : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { renderCardPage, renderCheckoutPage, escapeHtml, escapeAttr } from \"@emulators/core\";\nimport type { CheckoutLineItem } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { stripeId, toUnixTimestamp, parseStripeBody, stripeError, stripeList } from \"../helpers.js\";\nimport type { StripeCheckoutSession } from \"../entities.js\";\n\nconst SERVICE_LABEL = \"Stripe\";\n\nfunction formatSession(s: StripeCheckoutSession, baseUrl: string) {\n return {\n id: s.stripe_id,\n object: \"checkout.session\",\n mode: s.mode,\n status: s.status,\n payment_status: s.payment_status,\n customer: s.customer_id,\n success_url: s.success_url,\n cancel_url: s.cancel_url,\n metadata: s.metadata,\n created: toUnixTimestamp(s.created_at),\n livemode: false,\n url: s.status === \"open\" ? `${baseUrl}/checkout/${s.stripe_id}` : null,\n };\n}\n\nexport function checkoutSessionRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const ss = getStripeStore(store);\n\n app.post(\"/v1/checkout/sessions\", async (c) => {\n const body = await parseStripeBody(c);\n if (!body.mode)\n return stripeError(c, 400, \"invalid_request_error\", \"Missing required param: mode.\", undefined, \"mode\");\n\n if (body.customer && !ss.customers.findOneBy(\"stripe_id\", body.customer as string)) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such customer: '${body.customer}'`,\n \"resource_missing\",\n \"customer\",\n );\n }\n\n const lineItems: Array<{ price: string; quantity: number }> = [];\n if (body.line_items) {\n if (!Array.isArray(body.line_items)) {\n return stripeError(c, 400, \"invalid_request_error\", \"line_items must be an array.\", undefined, \"line_items\");\n }\n for (let i = 0; i < body.line_items.length; i++) {\n const li = body.line_items[i] as Record<string, unknown>;\n if (!li || typeof li !== \"object\") {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `Invalid line_items[${i}]: must be an object.`,\n undefined,\n `line_items[${i}]`,\n );\n }\n if (!li.price || typeof li.price !== \"string\") {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `Missing required param: line_items[${i}][price].`,\n undefined,\n `line_items[${i}][price]`,\n );\n }\n if (!ss.prices.findOneBy(\"stripe_id\", li.price)) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such price: '${li.price}'`,\n \"resource_missing\",\n `line_items[${i}][price]`,\n );\n }\n const qty = typeof li.quantity === \"number\" ? li.quantity : parseInt(li.quantity as string, 10);\n if (!Number.isFinite(qty) || qty < 1) {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `Invalid line_items[${i}][quantity]: must be a positive integer.`,\n undefined,\n `line_items[${i}][quantity]`,\n );\n }\n lineItems.push({ price: li.price, quantity: qty });\n }\n }\n\n const session = ss.checkoutSessions.insert({\n stripe_id: stripeId(\"cs\"),\n mode: body.mode as StripeCheckoutSession[\"mode\"],\n status: \"open\",\n payment_status: \"unpaid\",\n customer_id: (body.customer as string) ?? null,\n success_url: (body.success_url as string) ?? null,\n cancel_url: (body.cancel_url as string) ?? null,\n line_items: lineItems,\n metadata: (body.metadata as Record<string, string>) ?? {},\n });\n return c.json(formatSession(session, baseUrl), 200);\n });\n\n app.get(\"/v1/checkout/sessions/:id\", (c) => {\n const session = ss.checkoutSessions.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!session)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such checkout session: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n return c.json(formatSession(session, baseUrl));\n });\n\n app.post(\"/v1/checkout/sessions/:id/expire\", async (c) => {\n const session = ss.checkoutSessions.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!session)\n return stripeError(\n c,\n 404,\n \"invalid_request_error\",\n `No such checkout session: '${c.req.param(\"id\")}'`,\n \"resource_missing\",\n );\n if (session.status !== \"open\") {\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n \"Only open sessions can be expired.\",\n \"checkout_session_not_open\",\n );\n }\n const updated = ss.checkoutSessions.update(session.id, { status: \"expired\" })!;\n\n await webhooks.dispatch(\n \"checkout.session.expired\",\n undefined,\n { type: \"checkout.session.expired\", data: { object: formatSession(updated, baseUrl) } },\n \"stripe\",\n );\n\n return c.json(formatSession(updated, baseUrl));\n });\n\n app.get(\"/v1/checkout/sessions\", (c) => {\n let items = ss.checkoutSessions.all();\n const customerId = c.req.query(\"customer\");\n const status = c.req.query(\"status\");\n const paymentStatus = c.req.query(\"payment_status\");\n if (customerId) items = items.filter((s) => s.customer_id === customerId);\n if (status) items = items.filter((s) => s.status === status);\n if (paymentStatus) items = items.filter((s) => s.payment_status === paymentStatus);\n return stripeList(c, items, \"/v1/checkout/sessions\", (s) => formatSession(s, baseUrl));\n });\n\n app.get(\"/checkout/:id\", (c) => {\n const session = ss.checkoutSessions.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!session) {\n return c.html(\n renderCardPage(\n \"Session Not Found\",\n \"This checkout session does not exist.\",\n '<p class=\"empty\">The session ID is invalid or has been removed.</p>',\n SERVICE_LABEL,\n ),\n 404,\n );\n }\n if (session.status !== \"open\") {\n return c.html(\n renderCardPage(\n \"Session Expired\",\n \"This checkout session is no longer available.\",\n `<p class=\"empty\">Status: ${escapeHtml(session.status)}</p>`,\n SERVICE_LABEL,\n ),\n );\n }\n\n const lineItems: CheckoutLineItem[] = session.line_items.map((li) => {\n const priceObj = ss.prices.findOneBy(\"stripe_id\", li.price);\n const product = priceObj ? ss.products.findOneBy(\"stripe_id\", priceObj.product_id) : null;\n const unitPrice = priceObj?.unit_amount ?? 0;\n return {\n name: product?.name ?? li.price,\n quantity: li.quantity,\n unitPrice,\n totalPrice: unitPrice * li.quantity,\n currency: priceObj?.currency ?? \"usd\",\n };\n });\n\n const subtotal = lineItems.reduce((sum, li) => sum + li.totalPrice, 0);\n const currency = lineItems.length > 0 ? lineItems[0].currency : \"usd\";\n\n return c.html(\n renderCheckoutPage(\n {\n lineItems,\n subtotal,\n total: subtotal,\n currency,\n sessionId: session.stripe_id,\n cancelUrl: session.cancel_url,\n },\n SERVICE_LABEL,\n ),\n );\n });\n\n app.post(\"/checkout/:id/complete\", async (c) => {\n const session = ss.checkoutSessions.findOneBy(\"stripe_id\", c.req.param(\"id\"));\n if (!session || session.status !== \"open\") {\n return c.redirect(\"/checkout/\" + c.req.param(\"id\"));\n }\n\n const updated = ss.checkoutSessions.update(session.id, { status: \"complete\", payment_status: \"paid\" })!;\n\n await webhooks.dispatch(\n \"checkout.session.completed\",\n undefined,\n { type: \"checkout.session.completed\", data: { object: formatSession(updated, baseUrl) } },\n \"stripe\",\n );\n\n if (session.success_url) {\n const url = session.success_url.replace(\"{CHECKOUT_SESSION_ID}\", updated.stripe_id);\n return c.redirect(url);\n }\n\n return c.html(\n renderCardPage(\n \"Payment Complete\",\n \"Your payment was successful.\",\n '<p class=\"empty check\">Payment received</p>',\n SERVICE_LABEL,\n ),\n );\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"../store.js\";\nimport { stripeId, parseStripeBody, stripeError } from \"../helpers.js\";\n\nexport function customerSessionRoutes({ app, store }: RouteContext): void {\n const ss = getStripeStore(store);\n\n app.post(\"/v1/customer_sessions\", async (c) => {\n const body = await parseStripeBody(c);\n if (!body.customer)\n return stripeError(c, 400, \"invalid_request_error\", \"Missing required param: customer.\", undefined, \"customer\");\n\n const customer = ss.customers.findOneBy(\"stripe_id\", body.customer as string);\n if (!customer)\n return stripeError(\n c,\n 400,\n \"invalid_request_error\",\n `No such customer: '${body.customer}'`,\n \"resource_missing\",\n \"customer\",\n );\n\n return c.json(\n {\n object: \"customer_session\" as const,\n client_secret: stripeId(\"cuss_secret\"),\n components: (body.components as Record<string, unknown>) ?? {},\n created: Math.floor(Date.now() / 1000),\n customer: customer.stripe_id,\n expires_at: Math.floor(Date.now() / 1000) + 1800,\n livemode: false,\n },\n 200,\n );\n });\n}\n","import type { Hono } from \"hono\";\nimport type { ServicePlugin, Store, WebhookDispatcher, TokenMap, AppEnv, RouteContext } from \"@emulators/core\";\nimport { getStripeStore } from \"./store.js\";\nimport { stripeId } from \"./helpers.js\";\nimport { customerRoutes } from \"./routes/customers.js\";\nimport { paymentIntentRoutes } from \"./routes/payment-intents.js\";\nimport { paymentMethodRoutes } from \"./routes/payment-methods.js\";\nimport { chargeRoutes } from \"./routes/charges.js\";\nimport { productRoutes } from \"./routes/products.js\";\nimport { priceRoutes } from \"./routes/prices.js\";\nimport { checkoutSessionRoutes } from \"./routes/checkout-sessions.js\";\nimport { customerSessionRoutes } from \"./routes/customer-sessions.js\";\n\nexport { getStripeStore, type StripeStore } from \"./store.js\";\nexport * from \"./entities.js\";\n\nexport interface StripeSeedConfig {\n port?: number;\n customers?: Array<{\n id?: string;\n email?: string;\n name?: string;\n description?: string;\n }>;\n products?: Array<{\n id?: string;\n name: string;\n description?: string;\n }>;\n prices?: Array<{\n id?: string;\n product_name: string;\n currency: string;\n unit_amount: number;\n }>;\n webhooks?: Array<{\n url: string;\n events: string[];\n secret?: string;\n }>;\n}\n\nfunction seedDefaults(store: Store, _baseUrl: string): void {\n const ss = getStripeStore(store);\n\n ss.customers.insert({\n stripe_id: stripeId(\"cus\"),\n email: \"test@example.com\",\n name: \"Test Customer\",\n description: null,\n metadata: {},\n });\n}\n\nexport function seedFromConfig(\n store: Store,\n _baseUrl: string,\n config: StripeSeedConfig,\n webhooks?: WebhookDispatcher,\n): void {\n const ss = getStripeStore(store);\n\n if (config.customers) {\n for (const c of config.customers) {\n if (c.email) {\n const existing = ss.customers.findOneBy(\"email\", c.email);\n if (existing) continue;\n }\n ss.customers.insert({\n stripe_id: c.id ?? stripeId(\"cus\"),\n email: c.email ?? null,\n name: c.name ?? null,\n description: c.description ?? null,\n metadata: {},\n });\n }\n }\n\n if (config.products) {\n for (const p of config.products) {\n const product = ss.products.insert({\n stripe_id: p.id ?? stripeId(\"prod\"),\n name: p.name,\n description: p.description ?? null,\n active: true,\n metadata: {},\n });\n\n const matchingPrices = config.prices?.filter((pr) => pr.product_name === p.name) ?? [];\n for (const pr of matchingPrices) {\n ss.prices.insert({\n stripe_id: pr.id ?? stripeId(\"price\"),\n product_id: product.stripe_id,\n currency: pr.currency.toLowerCase(),\n unit_amount: pr.unit_amount,\n type: \"one_time\",\n active: true,\n metadata: {},\n });\n }\n }\n }\n\n if (config.webhooks && webhooks) {\n for (const wh of config.webhooks) {\n webhooks.register({\n url: wh.url,\n events: wh.events,\n active: true,\n secret: wh.secret,\n owner: \"stripe\",\n });\n }\n }\n}\n\nexport const stripePlugin: ServicePlugin = {\n name: \"stripe\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n customerRoutes(ctx);\n paymentMethodRoutes(ctx);\n paymentIntentRoutes(ctx);\n chargeRoutes(ctx);\n productRoutes(ctx);\n priceRoutes(ctx);\n checkoutSessionRoutes(ctx);\n customerSessionRoutes(ctx);\n },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default stripePlugin;\n"],"mappings":";;;ACAA,SAAS,mBAAmB;AcA5B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YA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AK,OAAO,UAAU;AAC/B,YAAM,UAAU,GAAG,SAAS,OAAO;QACjC,WAAW,EAAE,MAAM,SAAS,MAAM;QAClC,MAAM,EAAE;QACR,aAAa,EAAE,eAAe;QAC9B,QAAQ;QACR,UAAU,CAAC;MACb,CAAC;AAED,YAAM,iBAAiB,OAAO,QAAQ,OAAO,CAAC,OAAO,GAAG,iBAAiB,EAAE,IAAI,KAAK,CAAC;AACrF,iBAAW,MAAM,gBAAgB;AAC/B,WAAG,OAAO,OAAO;UACf,WAAW,GAAG,MAAM,SAAS,OAAO;UACpC,YAAY,QAAQ;UACpB,UAAU,GAAG,SAAS,YAAY;UAClC,aAAa,GAAG;UAChB,MAAM;UACN,QAAQ;UACR,UAAU,CAAC;QACb,CAAC;MACH;IACF;EACF;AAEA,MAAI,OAAO,YAAY,UAAU;AAC/B,eAAW,MAAM,OAAO,UAAU;AAChC,eAAS,SAAS;QAChB,KAAK,GAAG;QACR,QAAQ,GAAG;QACX,QAAQ;QACR,QAAQ,GAAG;QACX,OAAO;MACT,CAAC;IACH;EACF;AACF;AAEO,IAAM,eAA8B;EACzC,MAAM;EACN,SAAS,KAAmB,OAAc,UAA6B,SAAiB,UAA2B;AACjH,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,mBAAe,GAAG;AAClB,wBAAoB,GAAG;AACvB,wBAAoB,GAAG;AACvB,iBAAa,GAAG;AAChB,kBAAc,GAAG;AACjB,gBAAY,GAAG;AACf,0BAAsB,GAAG;AACzB,0BAAsB,GAAG;EAC3B;EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":["formatProduct"]}
@@ -3,7 +3,7 @@ import {
3
3
  exportJWK,
4
4
  generateKeyPair
5
5
  } from "./chunk-D6EKRYGP.js";
6
- import "./chunk-TEPNEZ63.js";
6
+ import "./chunk-AQ2CLRU3.js";
7
7
 
8
8
  // ../@emulators/microsoft/dist/index.js
9
9
  import { randomUUID } from "crypto";
@@ -42,6 +42,7 @@ var FONTS = {
42
42
  "geist-sans.woff2": readFileSync(join(__dirname, "fonts", "geist-sans.woff2")),
43
43
  "GeistPixel-Square.woff2": readFileSync(join(__dirname, "fonts", "GeistPixel-Square.woff2"))
44
44
  };
45
+ var FAVICON = readFileSync(join(__dirname, "fonts", "favicon.ico"));
45
46
  function escapeHtml(s) {
46
47
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
47
48
  }
@@ -193,6 +194,132 @@ body{
193
194
  .app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}
194
195
  .app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}
195
196
  .empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}
197
+
198
+ .inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}
199
+ .inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}
200
+ .inspector-tabs a{
201
+ padding:7px 16px;border-radius:6px;text-decoration:none;
202
+ font-size:.8125rem;color:#1a8c00;border:1px solid transparent;
203
+ transition:color .15s,border-color .15s;
204
+ }
205
+ .inspector-tabs a:hover{color:#33ff00;}
206
+ .inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}
207
+ .inspector-section{margin-bottom:24px;}
208
+ .inspector-section h2{
209
+ font-family:'Geist Pixel',monospace;
210
+ font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;
211
+ }
212
+ .inspector-section h3{
213
+ font-family:'Geist Pixel',monospace;
214
+ font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;
215
+ }
216
+ .inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}
217
+ .inspector-table th,.inspector-table td{
218
+ text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;
219
+ font-size:.8125rem;
220
+ }
221
+ .inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}
222
+ .inspector-table td{color:#33ff00;}
223
+ .inspector-table tbody tr{transition:background .1s;}
224
+ .inspector-table tbody tr:hover{background:#0a3300;}
225
+ .inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}
226
+
227
+ .checkout-layout{
228
+ display:flex;min-height:calc(100vh - 42px);
229
+ }
230
+ .checkout-summary{
231
+ flex:1;background:#020;padding:48px 40px 48px 10%;
232
+ display:flex;flex-direction:column;justify-content:center;
233
+ border-right:1px solid #0a3300;
234
+ }
235
+ .checkout-form-side{
236
+ flex:1;background:#000;padding:48px 10% 48px 40px;
237
+ display:flex;flex-direction:column;justify-content:center;
238
+ }
239
+ .checkout-merchant{
240
+ display:flex;align-items:center;gap:10px;margin-bottom:6px;
241
+ }
242
+ .checkout-merchant-name{
243
+ font-family:'Geist Pixel',monospace;
244
+ font-size:.9375rem;font-weight:600;color:#33ff00;
245
+ }
246
+ .checkout-test-badge{
247
+ font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;
248
+ background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;
249
+ }
250
+ .checkout-total{
251
+ font-family:'Geist Pixel',monospace;
252
+ font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;
253
+ }
254
+ .checkout-line-item{
255
+ display:flex;align-items:center;gap:14px;padding:14px 0;
256
+ border-bottom:1px solid #0a3300;
257
+ }
258
+ .checkout-line-item:first-child{border-top:1px solid #0a3300;}
259
+ .checkout-item-icon{
260
+ width:42px;height:42px;border-radius:6px;background:#0a3300;
261
+ display:flex;align-items:center;justify-content:center;flex-shrink:0;
262
+ font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;
263
+ }
264
+ .checkout-item-details{flex:1;min-width:0;}
265
+ .checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}
266
+ .checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}
267
+ .checkout-item-price{
268
+ font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;
269
+ }
270
+ .checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}
271
+ .checkout-totals{margin-top:20px;}
272
+ .checkout-totals-row{
273
+ display:flex;justify-content:space-between;padding:6px 0;
274
+ font-size:.8125rem;color:#1a8c00;
275
+ }
276
+ .checkout-totals-row.total{
277
+ border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;
278
+ font-size:.9375rem;font-weight:600;color:#33ff00;
279
+ }
280
+ .checkout-form-section{margin-bottom:24px;}
281
+ .checkout-form-label{
282
+ font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;
283
+ }
284
+ .checkout-input{
285
+ width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;
286
+ background:#020;color:#33ff00;font:inherit;font-size:.875rem;
287
+ transition:border-color .15s;outline:none;
288
+ }
289
+ .checkout-input:focus{border-color:#33ff00;}
290
+ .checkout-input::placeholder{color:#116600;}
291
+ .checkout-card-box{
292
+ border:1px solid #0a3300;border-radius:6px;padding:14px;
293
+ background:#020;
294
+ }
295
+ .checkout-card-row{
296
+ display:flex;gap:12px;margin-top:10px;
297
+ }
298
+ .checkout-card-row .checkout-input{flex:1;}
299
+ .checkout-sim-note{
300
+ font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;
301
+ font-style:italic;
302
+ }
303
+ .checkout-pay-btn{
304
+ width:100%;padding:14px;border:none;border-radius:8px;
305
+ background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;
306
+ cursor:pointer;transition:background .15s;
307
+ font-family:'Geist Pixel',monospace;
308
+ }
309
+ .checkout-pay-btn:hover{background:#44ff22;}
310
+ .checkout-cancel{
311
+ text-align:center;margin-top:14px;
312
+ }
313
+ .checkout-cancel a{
314
+ color:#1a8c00;text-decoration:none;font-size:.8125rem;
315
+ transition:color .15s;
316
+ }
317
+ .checkout-cancel a:hover{color:#33ff00;}
318
+ @media(max-width:768px){
319
+ .checkout-layout{flex-direction:column;}
320
+ .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}
321
+ .checkout-form-side{padding:32px 20px;}
322
+ }
196
323
  `;
197
324
  var POWERED_BY = `<div class="powered-by">Powered by <a href="https://emulate.dev" target="_blank" rel="noopener">emulate</a></div>`;
198
325
  function emuBar(service) {
@@ -212,6 +339,7 @@ function head(title) {
212
339
  <head>
213
340
  <meta charset="utf-8"/>
214
341
  <meta name="viewport" content="width=device-width,initial-scale=1"/>
342
+ <link rel="icon" href="/_emulate/favicon.ico"/>
215
343
  <title>${escapeHtml(title)} | emulate</title>
216
344
  <style>${CSS}</style>
217
345
  </head>`;
@@ -243,6 +371,25 @@ ${emuBar(service)}
243
371
  ${POWERED_BY}
244
372
  </body></html>`;
245
373
  }
374
+ function renderFormPostPage(action, fields, service) {
375
+ const hiddens = Object.entries(fields).filter(([, v]) => v != null).map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}"/>`).join("\n");
376
+ return `${head("Redirecting")}
377
+ <body onload="document.forms[0].submit()">
378
+ ${emuBar(service)}
379
+ <div class="content">
380
+ <div class="content-inner" style="text-align:center">
381
+ <div class="card-subtitle">Redirecting&hellip;</div>
382
+ <form method="POST" action="${escapeAttr(action)}">
383
+ ${hiddens}
384
+ <noscript><button type="submit" class="user-btn" style="margin-top:12px;justify-content:center">
385
+ <span class="user-login">Continue</span>
386
+ </button></noscript>
387
+ </form>
388
+ </div>
389
+ </div>
390
+ ${POWERED_BY}
391
+ </body></html>`;
392
+ }
246
393
  function renderUserButton(opts) {
247
394
  const hiddens = Object.entries(opts.hiddenFields).map(([k, v]) => `<input type="hidden" name="${escapeAttr(k)}" value="${escapeAttr(v)}"/>`).join("");
248
395
  const nameLine = opts.name ? `<div class="user-meta">${escapeHtml(opts.name)}</div>` : "";
@@ -360,18 +507,24 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
360
507
  });
361
508
  app.get("/:tenant/v2.0/.well-known/openid-configuration", (c) => {
362
509
  const tenant = c.req.param("tenant");
363
- return c.json(oidcConfig(tenant === "common" || tenant === "organizations" || tenant === "consumers" ? DEFAULT_TENANT_ID : tenant));
510
+ return c.json(
511
+ oidcConfig(
512
+ tenant === "common" || tenant === "organizations" || tenant === "consumers" ? DEFAULT_TENANT_ID : tenant
513
+ )
514
+ );
364
515
  });
365
516
  app.get("/discovery/v2.0/keys", async (c) => {
366
517
  const { publicKey } = await keyPairPromise;
367
518
  const jwk = await exportJWK(publicKey);
368
519
  return c.json({
369
- keys: [{
370
- ...jwk,
371
- kid: KID,
372
- use: "sig",
373
- alg: "RS256"
374
- }]
520
+ keys: [
521
+ {
522
+ ...jwk,
523
+ kid: KID,
524
+ use: "sig",
525
+ alg: "RS256"
526
+ }
527
+ ]
375
528
  });
376
529
  });
377
530
  app.get("/oauth2/v2.0/authorize", (c) => {
@@ -395,7 +548,11 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
395
548
  }
396
549
  if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
397
550
  return c.html(
398
- renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
551
+ renderErrorPage(
552
+ "Redirect URI mismatch",
553
+ "The redirect_uri is not registered for this application.",
554
+ SERVICE_LABEL
555
+ ),
399
556
  400
400
557
  );
401
558
  }
@@ -448,7 +605,11 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
448
605
  }
449
606
  if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {
450
607
  return c.html(
451
- renderErrorPage("Redirect URI mismatch", "The redirect_uri is not registered for this application.", SERVICE_LABEL),
608
+ renderErrorPage(
609
+ "Redirect URI mismatch",
610
+ "The redirect_uri is not registered for this application.",
611
+ SERVICE_LABEL
612
+ ),
452
613
  400
453
614
  );
454
615
  }
@@ -466,17 +627,7 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
466
627
  });
467
628
  debug("microsoft.oauth", `[Microsoft callback] code=${code.slice(0, 8)}... email=${email}`);
468
629
  if (response_mode === "form_post") {
469
- const html = `<!DOCTYPE html>
470
- <html>
471
- <head><title>Submit</title></head>
472
- <body onload="document.forms[0].submit()">
473
- <form method="POST" action="${escapeAttr(redirect_uri)}">
474
- <input type="hidden" name="code" value="${escapeAttr(code)}" />
475
- <input type="hidden" name="state" value="${escapeAttr(state)}" />
476
- </form>
477
- </body>
478
- </html>`;
479
- return c.html(html);
630
+ return c.html(renderFormPostPage(redirect_uri, { code, state }, SERVICE_LABEL));
480
631
  }
481
632
  const url = new URL(redirect_uri);
482
633
  url.searchParams.set("code", code);
@@ -537,7 +688,13 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
537
688
  }
538
689
  if (pending.redirectUri && redirect_uri && pending.redirectUri !== redirect_uri) {
539
690
  pendingMap.delete(code);
540
- return c.json({ error: "invalid_grant", error_description: "The redirect_uri does not match the one used in the authorization request." }, 400);
691
+ return c.json(
692
+ {
693
+ error: "invalid_grant",
694
+ error_description: "The redirect_uri does not match the one used in the authorization request."
695
+ },
696
+ 400
697
+ );
541
698
  }
542
699
  if (pending.codeChallenge !== null) {
543
700
  if (code_verifier === void 0) {
@@ -643,7 +800,13 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
643
800
  scope: scope || ".default"
644
801
  });
645
802
  }
646
- return c.json({ error: "unsupported_grant_type", error_description: "Only authorization_code, refresh_token, and client_credentials are supported." }, 400);
803
+ return c.json(
804
+ {
805
+ error: "unsupported_grant_type",
806
+ error_description: "Only authorization_code, refresh_token, and client_credentials are supported."
807
+ },
808
+ 400
809
+ );
647
810
  });
648
811
  app.get("/oidc/userinfo", (c) => {
649
812
  const authUser = c.get("authUser");
@@ -720,12 +883,15 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
720
883
  const userId = c.req.param("id");
721
884
  const user = ms.users.findOneBy("oid", userId);
722
885
  if (!user) {
723
- return c.json({
724
- error: {
725
- code: "Request_ResourceNotFound",
726
- message: `Resource '${userId}' does not exist or one of its queried reference-property objects are not present.`
727
- }
728
- }, 404);
886
+ return c.json(
887
+ {
888
+ error: {
889
+ code: "Request_ResourceNotFound",
890
+ message: `Resource '${userId}' does not exist or one of its queried reference-property objects are not present.`
891
+ }
892
+ },
893
+ 404
894
+ );
729
895
  }
730
896
  return c.json({
731
897
  "@odata.context": `${baseUrl}/v1.0/$metadata#users/$entity`,
@@ -742,9 +908,7 @@ function oauthRoutes({ app, store, baseUrl, tokenMap }) {
742
908
  if (post_logout_redirect_uri) {
743
909
  const allClients = ms.oauthClients.all();
744
910
  if (allClients.length > 0) {
745
- const allowed = allClients.some(
746
- (client) => matchesRedirectUri(post_logout_redirect_uri, client.redirect_uris)
747
- );
911
+ const allowed = allClients.some((client) => matchesRedirectUri(post_logout_redirect_uri, client.redirect_uris));
748
912
  if (!allowed) {
749
913
  return c.text("Invalid post_logout_redirect_uri", 400);
750
914
  }
@@ -840,4 +1004,4 @@ export {
840
1004
  microsoftPlugin,
841
1005
  seedFromConfig
842
1006
  };
843
- //# sourceMappingURL=dist-RMK3BS5M.js.map
1007
+ //# sourceMappingURL=dist-ETHHYBGF.js.map