@crvouga/mockingbird-service-wholescripts 3.13.0 → 3.14.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.
- package/CHANGELOG.md +11 -1
- package/dist/chunk-5IGBFNTP.js +116 -0
- package/dist/chunk-5IGBFNTP.js.map +7 -0
- package/dist/chunk-RTRYBGHC.js +774 -0
- package/dist/chunk-RTRYBGHC.js.map +7 -0
- package/dist/cli.js +3 -5
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +102 -94
- package/dist/index.js +1 -2
- package/dist/server.d.ts +45 -37
- package/dist/server.js +2 -3
- package/package.json +3 -2
- package/dist/admin-ui.js +0 -27
- package/dist/admin-ui.js.map +0 -7
- package/dist/chunk-2H44NU3T.js +0 -7
- package/dist/chunk-2H44NU3T.js.map +0 -7
- package/dist/chunk-A475SKFT.js +0 -6103
- package/dist/chunk-A475SKFT.js.map +0 -7
- package/dist/chunk-F36ZGEH5.js +0 -5165
- package/dist/chunk-F36ZGEH5.js.map +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["<define:__MOCKINGBIRD_ADMIN_BRAND__>", "mockingbird-service-runtime:@crvouga/mockingbird-runtime/service", "../src/catalog.ts", "../src/generated/openapi.ts", "../src/state.ts", "../src/runtime.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["{\"vendor\":\"Wholescripts\",\"website\":\"https://www.wholescripts.com\",\"docs\":\"https://www.wholescripts.com/api\",\"guide\":\"https://mockingbird.chrisvouga.dev/services/wholescripts\",\"logo\":\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAFVAAABVQHWX0dyAAABO0lEQVQ4jYVTwXHCMBDcMPnHJdABdBBbDYQn+qUCDR3EVBBHDcBP39CAhlQQ6MDpIB04c/YesWUDN6OxLd/u7e1JaJpmcq2Lj3xqP10zXI/cGl9b41+vZgB4EBYNa3wGYBmiO6L7FvAOwA+AfYiuvEcgwGcCqhBdZY0/AVgwRfZXIbrTiMAavwHwnhQoAEjVOQBRs+JzE6LbS8KM4HkPvAXwlRCVbEtAUmhHzMXEXwBnvh9HTnWGVvwn8g9U0hGE6ITgcwT7jxWrlyTJ9M+tMaoyVfVNYE6jbxJIpS3dzii7YP9536PHBHjWMyBVOZkFVx2ia6Vb45cKmDpIFccmSU9JgQPVvFFheVHAsYiRemim4oVLfRl4IL21s70ToqLQVgctUImeOK0k0d4F3oe6nz8iSPxozeoZOwwAf4vApBOhud1XAAAAAElFTkSuQmCC\",\"color\":null,\"description\":\"Wholescripts is a practitioner supplement dispensary that fulfils professional-grade and private-label supplement orders.\"}", "export * from \"@crvouga/mockingbird-runtime/service\"\nimport { PACKAGE_VERSION as SHARED_VERSION, createRuntime as sharedRuntime } from \"@crvouga/mockingbird-runtime/service\"\nexport const PACKAGE_VERSION =\n typeof __MOCKINGBIRD_PACKAGE_VERSION__ === \"string\" ? __MOCKINGBIRD_PACKAGE_VERSION__ : SHARED_VERSION\nconst ADMIN_BRAND =\n typeof __MOCKINGBIRD_ADMIN_BRAND__ === \"object\" ? __MOCKINGBIRD_ADMIN_BRAND__ : undefined\nexport const createRuntime = (options) =>\n sharedRuntime({\n ...options,\n version: options.version ?? PACKAGE_VERSION,\n adminBrand: options.adminBrand ?? ADMIN_BRAND,\n })\n", "/** MedPax-specific pricing and stock, present on products that can go into a MedPax pack. */\nexport type MedPaxDetails = {\n name: string\n genericName: string\n quantity: number\n wholesalePrice: number\n retailPrice: number\n}\n\n/** One `GET /api/Orders/ProductList` row, in the field names our consumers parse. */\nexport type Product = {\n productName: string\n sku: string\n medPaxSku: string\n categories: string\n retailPrice: number\n upc: string\n descriptionShort: string\n descriptionFull?: string\n brand: string\n productImage: string\n quantity: number\n countUnit: string\n wholesalePrice: number\n supplementFactsHTML: string\n defaultDosing: { time: string; qty: number }[]\n medPaxDetails?: MedPaxDetails | null\n}\n\n/** One `medPaxPills` row of `GET /api/Orders/PrivateLabelProductList`. */\nexport type MedPaxPill = {\n sku: string\n genericName: string\n privateLabelName: string\n quantity: number\n}\n\n/** One `privateLabelCartons` row of `GET /api/Orders/PrivateLabelProductList`. */\nexport type PrivateLabelCarton = {\n sku: string\n name: string\n cartonImage: string\n quantity: number\n}\n\nexport type Catalog = {\n products: Product[]\n medPaxPills: MedPaxPill[]\n privateLabelCartons: PrivateLabelCarton[]\n}\n\n/** The MedPax box SKU the supplement scheduler orders every pack under (`acme_blend_sku` in its config). */\nexport const MEDPAX_BOX_SKU = \"000000000200095263\"\n\nconst product = (\n row: Omit<Product, \"upc\" | \"productImage\" | \"supplementFactsHTML\" | \"brand\"> &\n Partial<Pick<Product, \"upc\" | \"productImage\" | \"supplementFactsHTML\" | \"brand\">>,\n): Product => ({\n upc: `1234567${row.sku.replace(/\\D/g, \"\").padStart(5, \"0\")}`,\n productImage: `https://example.com/${row.sku.toLowerCase()}.jpg`,\n supplementFactsHTML: \"<div>Facts</div>\",\n brand: \"Test Brand\",\n ...row,\n})\n\n/**\n * The catalog every namespace starts with. The rows are the ones our consumers' own tests use\n * (the consumer app's `wholescripts-service.test.ts`: Test Product 1/2,\n * Vitamin D3, Vitamin D Complex, Calcium, Protein Powder, PL001, PLC001), with the fixture's\n * repeated `medPaxSku`s made unique, plus the scheduler's MedPax box and `medPaxDetails` rows the\n * scheduler's catalog sync reads. `Protein Powder` is out of stock (`instockonly` drops it).\n */\nexport const DEFAULT_CATALOG: Catalog = {\n products: [\n product({\n productName: \"Test Product 1\",\n sku: \"SKU001\",\n medPaxSku: \"MP001\",\n categories: \"Supplements\",\n retailPrice: 29.99,\n upc: \"123456789001\",\n descriptionShort: \"Test product 1 description\",\n productImage: \"https://example.com/image1.jpg\",\n quantity: 100,\n countUnit: \"capsules\",\n wholesalePrice: 19.99,\n defaultDosing: [{ time: \"AM\", qty: 1 }],\n }),\n product({\n productName: \"Test Product 2\",\n sku: \"SKU002\",\n medPaxSku: \"MP002\",\n categories: \"Vitamins\",\n retailPrice: 39.99,\n upc: \"123456789002\",\n descriptionShort: \"Test product 2 description\",\n productImage: \"https://example.com/image2.jpg\",\n quantity: 50,\n countUnit: \"tablets\",\n wholesalePrice: 29.99,\n defaultDosing: [{ time: \"PM\", qty: 2 }],\n }),\n product({\n productName: \"Vitamin D3\",\n sku: \"VD001\",\n medPaxSku: \"MPVD001\",\n categories: \"Vitamins,Supplements\",\n retailPrice: 19.99,\n descriptionShort: \"Vitamin D3 supplement\",\n quantity: 100,\n countUnit: \"capsules\",\n wholesalePrice: 14.99,\n defaultDosing: [{ time: \"AM\", qty: 1 }],\n medPaxDetails: {\n name: \"Vitamin D3 5000 IU\",\n genericName: \"Cholecalciferol\",\n quantity: 400,\n wholesalePrice: 0.12,\n retailPrice: 0.2,\n },\n }),\n product({\n productName: \"Vitamin D Complex\",\n sku: \"VD002\",\n medPaxSku: \"MPVD002\",\n categories: \"Vitamins\",\n retailPrice: 29.99,\n descriptionShort: \"Vitamin D complex supplement\",\n quantity: 50,\n countUnit: \"tablets\",\n wholesalePrice: 24.99,\n defaultDosing: [{ time: \"PM\", qty: 2 }],\n }),\n product({\n productName: \"Calcium\",\n sku: \"CA001\",\n medPaxSku: \"MPCA001\",\n categories: \"Minerals\",\n retailPrice: 19.99,\n descriptionShort: \"Calcium supplement\",\n quantity: 100,\n countUnit: \"capsules\",\n wholesalePrice: 14.99,\n defaultDosing: [{ time: \"AM\", qty: 1 }],\n medPaxDetails: {\n name: \"Calcium Citrate\",\n genericName: \"Calcium citrate\",\n quantity: 0,\n wholesalePrice: 0.1,\n retailPrice: 0.18,\n },\n }),\n product({\n productName: \"Protein Powder\",\n sku: \"PP001\",\n medPaxSku: \"MPPP001\",\n categories: \"Supplements\",\n retailPrice: 49.99,\n descriptionShort: \"Protein powder\",\n quantity: 0,\n countUnit: \"grams\",\n wholesalePrice: 34.99,\n defaultDosing: [{ time: \"AM\", qty: 1 }],\n }),\n product({\n productName: \"Acme Longevity Blend MedPax Box\",\n sku: MEDPAX_BOX_SKU,\n medPaxSku: \"\",\n categories: \"MedPax\",\n retailPrice: 0,\n descriptionShort: \"30-day AM/PM MedPax carton\",\n quantity: 1000,\n countUnit: \"box\",\n wholesalePrice: 0,\n defaultDosing: [],\n }),\n ],\n medPaxPills: [\n {\n sku: \"PL001\",\n genericName: \"Generic Name 1\",\n privateLabelName: \"Private Label Product 1\",\n quantity: 30,\n },\n {\n sku: \"MP001\",\n genericName: \"Generic Pill 1\",\n privateLabelName: \"MedPax Pill 1\",\n quantity: 30,\n },\n {\n sku: \"MP002\",\n genericName: \"Generic Pill 2\",\n privateLabelName: \"MedPax Pill 2\",\n quantity: 60,\n },\n ],\n privateLabelCartons: [\n {\n sku: \"PLC001\",\n name: \"Private Label Carton 1\",\n cartonImage: \"https://example.com/carton1.jpg\",\n quantity: 30,\n },\n ],\n}\n\n/** Every SKU a submit may reference: product SKUs, MedPax SKUs, pill and carton SKUs. */\nexport const orderableSkus = (catalog: Catalog): Set<string> => {\n const skus = new Set<string>()\n for (const p of catalog.products) {\n skus.add(p.sku)\n if (p.medPaxSku) skus.add(p.medPaxSku)\n }\n for (const pill of catalog.medPaxPills) skus.add(pill.sku)\n for (const carton of catalog.privateLabelCartons) skus.add(carton.sku)\n return skus\n}\n\n/** The wholesale unit price a SKU is billed at (0 for cartons and unknown SKUs). */\nexport const unitPrice = (catalog: Catalog, sku: string): number => {\n for (const p of catalog.products) {\n if (p.sku === sku) return p.wholesalePrice\n if (p.medPaxSku && p.medPaxSku === sku)\n return p.medPaxDetails?.wholesalePrice ?? p.wholesalePrice\n }\n return 0\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst text = (row: Record<string, unknown>, key: string, where: string, fallback?: string) => {\n const value = row[key]\n if (value === undefined && fallback !== undefined) return fallback\n if (typeof value !== \"string\") throw new Error(`${where}.${key} must be a string`)\n return value\n}\n\nconst count = (row: Record<string, unknown>, key: string, where: string) => {\n const value = row[key] ?? 0\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new Error(`${where}.${key} must be a number`)\n return value\n}\n\nconst list = (value: unknown, where: string): Record<string, unknown>[] => {\n if (!Array.isArray(value)) throw new Error(`${where} must be an array`)\n return value.map((row, index) => {\n if (!isRecord(row)) throw new Error(`${where}[${index}] must be an object`)\n return row\n })\n}\n\n/**\n * Check a catalog document and fill the fields a row may leave out. The document is\n * `{products?, medPaxPills?, privateLabelCartons?}` (or a bare array of products); a row needs\n * its `sku` (and a product its `productName`), and every other string defaults to `\"\"`,\n * every number to `0`, and `defaultDosing` to none. Throws a message naming the bad field.\n */\nexport const parseCatalogDocument = (input: unknown): Partial<Catalog> => {\n const document = Array.isArray(input) ? { products: input } : input\n if (!isRecord(document))\n throw new Error(\"expected {products?, medPaxPills?, privateLabelCartons?}\")\n for (const key of Object.keys(document))\n if (![\"products\", \"medPaxPills\", \"privateLabelCartons\"].includes(key))\n throw new Error(`unknown key ${JSON.stringify(key)}`)\n const out: Partial<Catalog> = {}\n if (document.products !== undefined)\n out.products = list(document.products, \"products\").map((row, index): Product => {\n const where = `products[${index}]`\n const sku = text(row, \"sku\", where)\n if (!sku) throw new Error(`${where}.sku must not be empty`)\n const base = {\n productName: text(row, \"productName\", where),\n sku,\n medPaxSku: text(row, \"medPaxSku\", where, \"\"),\n categories: text(row, \"categories\", where, \"\"),\n retailPrice: count(row, \"retailPrice\", where),\n upc: text(row, \"upc\", where, \"\"),\n descriptionShort: text(row, \"descriptionShort\", where, \"\"),\n brand: text(row, \"brand\", where, \"\"),\n productImage: text(row, \"productImage\", where, \"\"),\n quantity: count(row, \"quantity\", where),\n countUnit: text(row, \"countUnit\", where, \"\"),\n wholesalePrice: count(row, \"wholesalePrice\", where),\n supplementFactsHTML: text(row, \"supplementFactsHTML\", where, \"\"),\n defaultDosing: Array.isArray(row.defaultDosing)\n ? (row.defaultDosing as Product[\"defaultDosing\"])\n : [],\n }\n return {\n ...base,\n ...(row.descriptionFull !== undefined\n ? { descriptionFull: text(row, \"descriptionFull\", where) }\n : {}),\n ...(row.medPaxDetails !== undefined\n ? {\n medPaxDetails:\n row.medPaxDetails === null\n ? null\n : (() => {\n const details = row.medPaxDetails\n if (!isRecord(details))\n throw new Error(`${where}.medPaxDetails must be an object`)\n const at = `${where}.medPaxDetails`\n return {\n name: text(details, \"name\", at, \"\"),\n genericName: text(details, \"genericName\", at, \"\"),\n quantity: count(details, \"quantity\", at),\n wholesalePrice: count(details, \"wholesalePrice\", at),\n retailPrice: count(details, \"retailPrice\", at),\n }\n })(),\n }\n : {}),\n }\n })\n if (document.medPaxPills !== undefined)\n out.medPaxPills = list(document.medPaxPills, \"medPaxPills\").map((row, index) => {\n const where = `medPaxPills[${index}]`\n const sku = text(row, \"sku\", where)\n if (!sku) throw new Error(`${where}.sku must not be empty`)\n return {\n sku,\n genericName: text(row, \"genericName\", where, \"\"),\n privateLabelName: text(row, \"privateLabelName\", where, \"\"),\n quantity: count(row, \"quantity\", where),\n }\n })\n if (document.privateLabelCartons !== undefined)\n out.privateLabelCartons = list(document.privateLabelCartons, \"privateLabelCartons\").map(\n (row, index) => {\n const where = `privateLabelCartons[${index}]`\n const sku = text(row, \"sku\", where)\n if (!sku) throw new Error(`${where}.sku must not be empty`)\n return {\n sku,\n name: text(row, \"name\", where, \"\"),\n cartonImage: text(row, \"cartonImage\", where, \"\"),\n quantity: count(row, \"quantity\", where),\n }\n },\n )\n return out\n}\n\nconst mergeRows = <T extends { sku: string }>(\n base: readonly T[],\n extra: readonly T[] = [],\n): T[] => {\n const replacements = new Map(extra.map((row) => [row.sku, row]))\n const kept = base.map((row) => replacements.get(row.sku) ?? row)\n const present = new Set(base.map((row) => row.sku))\n const added = new Map<string, T>()\n for (const row of extra) if (!present.has(row.sku)) added.set(row.sku, row)\n return [...kept, ...added.values()]\n}\n\n/**\n * Lay `extra` onto `base`: a row with a SKU `base` already has replaces it in place, any other\n * is appended, and a list `extra` leaves out is kept as it is.\n */\nexport const mergeCatalog = (base: Catalog, extra: Partial<Catalog>): Catalog => ({\n products: mergeRows(base.products, extra.products),\n medPaxPills: mergeRows(base.medPaxPills, extra.medPaxPills),\n privateLabelCartons: mergeRows(base.privateLabelCartons, extra.privateLabelCartons),\n})\n", "// Generated by @crvouga/mockingbird-openapi-codegen from openapi.yaml. Do not edit.\n\nimport type { OpenAPIDocument } from \"@crvouga/mockingbird-openapi\"\n\nexport const document: OpenAPIDocument = JSON.parse(`{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"Wholescripts supplement fulfilment API (Mockingbird subset)\",\"description\":\"Stateful emulator subset of the Wholescripts ordering API: the product and private-label\\\\n(MedPax) catalogs, order submit, status polling and cancel. Hand-authored from the\\\\nconsumers' zod schemas and clients (the vendor publishes no spec).\\\\n\",\"version\":\"1\",\"x-mockingbird-upstream\":{\"note\":\"Hand-authored from the wire shapes our consumers read and write (backend and EMR wholescripts.types.ts zod schemas, the supplement scheduler's Python client, adapter and mappers).\"}},\"servers\":[{\"url\":\"https://api.wholescripts.com\"}],\"security\":[{\"basicAuth\":[]}],\"paths\":{\"/api/Orders/PrivateLabelProductList\":{\"get\":{\"operationId\":\"GetPrivateLabelProductList\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"responses\":{\"200\":{\"description\":\"Private-label (MedPax) catalog\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/PrivateLabelProductList\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/api/Orders/ProductList\":{\"get\":{\"operationId\":\"GetProductList\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"instockonly\",\"in\":\"query\",\"required\":false,\"description\":\"\\`true\\` keeps only rows with quantity > 0 (the EMR sends it).\",\"schema\":{\"type\":\"string\",\"enum\":[\"true\",\"false\"]}},{\"name\":\"limit\",\"in\":\"query\",\"required\":false,\"schema\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":1000}},{\"name\":\"search\",\"in\":\"query\",\"required\":false,\"description\":\"Case-insensitive match on name, SKU, MedPax SKU, brand or categories (the supplement scheduler).\",\"schema\":{\"type\":\"string\",\"maxLength\":40}}],\"responses\":{\"200\":{\"description\":\"Products\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Product\"}}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/api/Orders/Submit\":{\"post\":{\"operationId\":\"SubmitOrder\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/OrderSubmitRequest\"}}}},\"responses\":{\"200\":{\"description\":\"Submit outcome. A rejected order (bad body, unknown SKU, payment failure) is still 200, with success false and the reason in msg.\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/OrderSubmitResponse\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/api/Orders/Status\":{\"get\":{\"operationId\":\"GetOrderStatus\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":true}},\"parameters\":[{\"name\":\"ordernum\",\"in\":\"query\",\"required\":true,\"schema\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"000000\"}}}],\"responses\":{\"200\":{\"description\":\"The order's status rows (empty for an unknown order number)\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/OrderStatus\"}}}}},\"400\":{\"description\":\"Missing ordernum\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AspNetError\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"}}}},\"/api/Orders/Cancel\":{\"post\":{\"operationId\":\"CancelOrder\",\"x-mockingbird\":{\"supported\":true,\"parity\":{\"enabled\":true,\"safe\":false}},\"requestBody\":{\"required\":true,\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"required\":[\"OrderNumber\"],\"properties\":{\"OrderNumber\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"order\",\"missing\":\"000000\"}}}}}}},\"responses\":{\"200\":{\"description\":\"Cancel outcome; success false when the order has progressed too far\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CancelResponse\"}}}},\"400\":{\"description\":\"Missing OrderNumber\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CancelResponse\"}}}},\"401\":{\"$ref\":\"#/components/responses/Unauthorized\"},\"404\":{\"description\":\"Unknown order\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/CancelResponse\"}}}}}}}},\"components\":{\"securitySchemes\":{\"basicAuth\":{\"type\":\"http\",\"scheme\":\"basic\"}},\"responses\":{\"Unauthorized\":{\"description\":\"Missing or wrong Basic credentials\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":\"#/components/schemas/AspNetError\"}}}}},\"schemas\":{\"AspNetError\":{\"type\":\"object\",\"required\":[\"Message\"],\"properties\":{\"Message\":{\"type\":\"string\"}}},\"DefaultDosing\":{\"type\":\"object\",\"required\":[\"time\",\"qty\"],\"properties\":{\"time\":{\"type\":\"string\"},\"qty\":{\"type\":\"number\"}}},\"MedPaxDetails\":{\"type\":\"object\",\"required\":[\"name\",\"genericName\",\"quantity\",\"wholesalePrice\",\"retailPrice\"],\"properties\":{\"name\":{\"type\":\"string\"},\"genericName\":{\"type\":\"string\"},\"quantity\":{\"type\":\"number\"},\"wholesalePrice\":{\"type\":\"number\"},\"retailPrice\":{\"type\":\"number\"}}},\"Product\":{\"type\":\"object\",\"required\":[\"productName\",\"sku\",\"medPaxSku\",\"categories\",\"retailPrice\",\"upc\",\"descriptionShort\",\"brand\",\"productImage\",\"quantity\",\"countUnit\",\"wholesalePrice\",\"supplementFactsHTML\",\"defaultDosing\"],\"properties\":{\"productName\":{\"type\":\"string\"},\"sku\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"sku\",\"identity\":true}},\"medPaxSku\":{\"type\":\"string\"},\"categories\":{\"type\":\"string\"},\"retailPrice\":{\"type\":\"number\"},\"upc\":{\"type\":\"string\"},\"descriptionShort\":{\"type\":\"string\"},\"descriptionFull\":{\"type\":\"string\"},\"brand\":{\"type\":\"string\"},\"productImage\":{\"type\":\"string\"},\"quantity\":{\"type\":\"number\"},\"countUnit\":{\"type\":\"string\"},\"wholesalePrice\":{\"type\":\"number\"},\"supplementFactsHTML\":{\"type\":\"string\"},\"defaultDosing\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/DefaultDosing\"}},\"medPaxDetails\":{\"oneOf\":[{\"$ref\":\"#/components/schemas/MedPaxDetails\"},{\"type\":\"null\"}]}}},\"PrivateLabelProductList\":{\"type\":\"object\",\"required\":[\"privateLabelProducts\",\"medPaxPills\",\"privateLabelCartons\"],\"properties\":{\"privateLabelProducts\":{\"type\":\"array\",\"items\":{}},\"medPaxPills\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"sku\",\"genericName\",\"privateLabelName\",\"quantity\"],\"properties\":{\"sku\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"sku\",\"identity\":true}},\"genericName\":{\"type\":\"string\"},\"privateLabelName\":{\"type\":\"string\"},\"quantity\":{\"type\":\"number\"}}}},\"privateLabelCartons\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"sku\",\"name\",\"cartonImage\",\"quantity\"],\"properties\":{\"sku\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"sku\",\"identity\":true}},\"name\":{\"type\":\"string\"},\"cartonImage\":{\"type\":\"string\"},\"quantity\":{\"type\":\"number\"}}}}}},\"MedPaxPill\":{\"type\":\"object\",\"required\":[\"Sku\",\"Quantity\",\"ItemTime\"],\"properties\":{\"productId\":{\"type\":\"string\",\"maxLength\":64},\"Sku\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"sku\",\"missing\":\"000000000000000000\"}},\"Quantity\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":1000},\"ItemTime\":{\"type\":\"string\",\"enum\":[\"AM\",\"PM\",\"AM with food\",\"PM with food\"]}}},\"OrderItem\":{\"type\":\"object\",\"required\":[\"Sku\",\"Quantity\"],\"properties\":{\"Sku\":{\"type\":\"string\",\"x-mockingbird-resource-ref\":{\"type\":\"sku\",\"missing\":\"000000000000000000\"}},\"Quantity\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":1000},\"MedPaxName\":{\"type\":[\"string\",\"null\"],\"maxLength\":60},\"MedPaxPills\":{\"type\":[\"array\",\"null\"],\"description\":\"The pills packed into one MedPax box. The vendor places boxes of at least 14 pills; the bound only keeps generated bodies small.\",\"maxItems\":30,\"items\":{\"$ref\":\"#/components/schemas/MedPaxPill\"}}}},\"OrderSubmitRequest\":{\"type\":\"object\",\"required\":[\"ShippingAddress\",\"Items\",\"ShippingMethod\"],\"properties\":{\"ShippingAddress\":{\"type\":\"object\",\"required\":[\"FName\",\"LName\",\"Address1\",\"City\",\"State\",\"Zip\"],\"properties\":{\"FName\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"LName\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"Address1\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":80},\"Address2\":{\"type\":[\"string\",\"null\"],\"maxLength\":80},\"City\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40},\"State\":{\"type\":\"string\",\"pattern\":\"^[A-Z]{2}$\"},\"Zip\":{\"type\":\"string\",\"pattern\":\"^[0-9]{5}(-[0-9]{4})?$\"},\"Email\":{\"type\":\"string\",\"format\":\"email\",\"maxLength\":120}}},\"Notes\":{\"type\":[\"string\",\"null\"],\"maxLength\":500},\"Items\":{\"type\":\"array\",\"minItems\":1,\"maxItems\":4,\"items\":{\"$ref\":\"#/components/schemas/OrderItem\"}},\"ShippingMethod\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":40}}},\"OrderSubmitResponse\":{\"type\":\"object\",\"required\":[\"orderNumber\",\"success\",\"msg\"],\"properties\":{\"orderNumber\":{\"type\":\"string\",\"x-mockingbird-resource\":{\"type\":\"order\",\"identity\":true}},\"success\":{\"type\":\"boolean\"},\"msg\":{\"type\":\"string\"}}},\"Tracking\":{\"type\":\"object\",\"required\":[\"trackingNumber\",\"carrier\"],\"properties\":{\"trackingNumber\":{\"type\":\"string\"},\"carrier\":{\"type\":\"string\"},\"trackingUrl\":{\"type\":\"string\"}}},\"OrderStatus\":{\"type\":\"object\",\"required\":[\"orderNumber\",\"orderDate\",\"salesOrder\",\"status\",\"tracking\",\"message\",\"subTotal\",\"shipMethod\",\"shipCharge\",\"discount\",\"tax\",\"serviceFee\",\"orderTotal\"],\"properties\":{\"orderNumber\":{\"type\":\"string\"},\"orderDate\":{\"type\":\"string\",\"x-mockingbird-volatile\":{\"kind\":\"timestamp\"}},\"salesOrder\":{\"type\":\"string\"},\"status\":{\"type\":\"string\"},\"tracking\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Tracking\"}},\"message\":{\"type\":\"string\"},\"subTotal\":{\"type\":\"number\"},\"shipMethod\":{\"type\":\"string\"},\"shipCharge\":{\"type\":\"number\"},\"discount\":{\"type\":\"number\"},\"tax\":{\"type\":\"number\"},\"serviceFee\":{\"type\":\"number\"},\"orderTotal\":{\"type\":\"number\"}}},\"CancelResponse\":{\"type\":\"object\",\"required\":[\"success\",\"msg\"],\"properties\":{\"success\":{\"type\":\"boolean\"},\"msg\":{\"type\":\"string\"}}}}}}`) as OpenAPIDocument\n\nexport type OperationId = \"GetPrivateLabelProductList\" | \"GetProductList\" | \"SubmitOrder\" | \"GetOrderStatus\" | \"CancelOrder\"\nexport type SupportedOperationId = \"GetPrivateLabelProductList\" | \"GetProductList\" | \"SubmitOrder\" | \"GetOrderStatus\" | \"CancelOrder\"\nexport const operationIds = [\"GetPrivateLabelProductList\",\"GetProductList\",\"SubmitOrder\",\"GetOrderStatus\",\"CancelOrder\"] as const\nexport const supportedOperationIds = [\"GetPrivateLabelProductList\",\"GetProductList\",\"SubmitOrder\",\"GetOrderStatus\",\"CancelOrder\"] as const\n", "import { Collection } from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport { type Catalog, DEFAULT_CATALOG } from \"./catalog.js\"\n\nexport type Tracking = { trackingNumber: string; carrier: string; trackingUrl?: string }\n\n/**\n * One order as Wholescripts reports it on `GET /api/Orders/Status`. The shipping address and\n * recipient (PHI) are validated on submit but never stored; only the SKUs and quantities are\n * kept, to price the order.\n */\nexport type OrderRecord = {\n orderNumber: string\n orderDate: string\n salesOrder: string\n status: string\n tracking: Tracking[]\n message: string\n subTotal: number\n shipMethod: string\n shipCharge: number\n discount: number\n tax: number\n serviceFee: number\n orderTotal: number\n items: { sku: string; quantity: number }[]\n /** Mock-clock epoch ms of creation, for auto-advance. */\n createdAtMs: number\n /** Steps of `autoAdvance.path` already applied. */\n advanced: number\n}\n\nexport type AutoAdvance = {\n /** Mock-clock delay between steps. */\n afterMs: number\n /** Statuses to walk through, e.g. `[\"Processing\", \"Complete\"]`. */\n path: string[]\n}\n\n/** Per-namespace knobs, set through `PUT /__admin/settings`; cleared on reset. */\nexport type Settings = {\n /** Only these Basic credentials are accepted; empty means any non-empty pair is. */\n accounts: { username: string; password: string }[]\n autoAdvance: AutoAdvance | null\n}\n\nexport const DEFAULT_SETTINGS: Settings = { accounts: [], autoAdvance: null }\n\n/** Order numbers start here, like the vendor's numeric web order numbers. */\nconst FIRST_ORDER_NUMBER = 700_001\n\nexport class WholescriptsState {\n readonly orders: Collection<OrderRecord>\n readonly catalogs: Collection<Catalog>\n readonly settings: Collection<Settings>\n\n constructor(\n sqlite: SqliteClient,\n namespace: string,\n private readonly seed: { catalog: Catalog | undefined; settings: Partial<Settings> },\n ) {\n this.orders = new Collection(sqlite, namespace, \"orders\")\n this.catalogs = new Collection(sqlite, namespace, \"catalog\")\n this.settings = new Collection(sqlite, namespace, \"settings\")\n this.ensureSeeded()\n }\n\n /** Re-apply the catalog and settings after a reset. */\n ensureSeeded(): void {\n if (!this.catalogs.has(\"catalog\")) {\n this.catalogs.insert(\"catalog\", this.seed.catalog ?? DEFAULT_CATALOG)\n }\n if (!this.settings.has(\"settings\")) {\n this.settings.insert(\"settings\", { ...DEFAULT_SETTINGS, ...this.seed.settings })\n }\n }\n\n catalog(): Catalog {\n return this.catalogs.get(\"catalog\") ?? DEFAULT_CATALOG\n }\n\n replaceCatalog(catalog: Catalog): Catalog {\n this.catalogs.insert(\"catalog\", catalog)\n return catalog\n }\n\n current(): Settings {\n return this.settings.get(\"settings\") ?? DEFAULT_SETTINGS\n }\n\n update(patch: Partial<Settings>): Settings {\n const next = { ...this.current(), ...patch }\n this.settings.insert(\"settings\", next)\n return next\n }\n\n nextOrderNumber(): string {\n return String(FIRST_ORDER_NUMBER + this.orders.count())\n }\n}\n", "import {\n type AdminRoutes,\n type Clock,\n createRuntime as createServiceRuntime,\n type FaultPreset,\n type MockControls,\n type RequestLog,\n type ServiceRuntime,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Catalog } from \"./catalog.js\"\nimport { document } from \"./generated/openapi.js\"\nimport { basicUsername, WHOLESCRIPTS_NAMESPACE, WholescriptsAPI } from \"./index.js\"\nimport type { AutoAdvance, Settings } from \"./state.js\"\n\n/**\n * Every named Wholescripts misbehaviour our consumers branch on, switched on with\n * `POST /__admin/faults {\"preset\": \"<name>\"}` (add `count` to limit it).\n */\nexport const WHOLESCRIPTS_PRESETS: Record<string, FaultPreset> = {\n submit_rejected: {\n description:\n \"Submit answers 200 {success: false, msg} (the backend and the scheduler both reject it)\",\n rules: [{ operationId: \"SubmitOrder\", effect: \"submit_rejected\" }],\n },\n submit_timeout: {\n description:\n \"Submit places the order, then drops the connection (the scheduler's 'order may have been placed')\",\n rules: [{ operationId: \"SubmitOrder\", effect: \"submit_timeout\" }],\n },\n status_empty: {\n description:\n \"Status answers [] even for a known order (backend returns null, the scheduler 'unknown')\",\n rules: [{ operationId: \"GetOrderStatus\", effect: \"status_empty\" }],\n },\n status_schema_drift: {\n description:\n \"Status rows drop salesOrder and stringify orderTotal (the backend zod check fails: data null)\",\n rules: [{ operationId: \"GetOrderStatus\", effect: \"status_schema_drift\" }],\n },\n server_error: {\n description: \"Every call answers 500 (the scheduler retries 5xx; the backend throws)\",\n rules: [{ status: 500, body: { Message: \"An error has occurred.\" } }],\n },\n unauthorized: {\n description: \"Every call answers 401, as with rotated Basic credentials\",\n rules: [{ status: 401, body: { Message: \"Authorization has been denied for this request.\" } }],\n },\n}\n\nexport type WholescriptsRuntimeOptions = {\n sqlite?: SqliteClient\n clock?: Clock\n seed?: number | string\n adminPrefix?: string\n adminKey?: string\n /** Admin controls to boot with: clock, latency, faults, seed, a starting snapshot. */\n adminControls?: MockControls\n onLog?: (entry: RequestLog) => void\n catalog?: Catalog\n settings?: Partial<Settings>\n /**\n * Run auto-advance on this real-time interval (ms). The served mock uses 100 ms; in-process\n * runtimes default to off (requests and `POST /__admin/tick` still advance).\n */\n tickMs?: number\n}\n\nexport type WholescriptsRuntime = ServiceRuntime<WholescriptsAPI> & {\n /** Stop the background ticker, if one runs. */\n stop(): void\n}\n\nconst json = (status: number, body: unknown) =>\n new Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } })\nconst adminError = (status: number, message: string) =>\n json(status, { error: { type: \"mockingbird_admin\", message } })\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n\nconst parseAutoAdvance = (value: unknown): AutoAdvance | null | string => {\n if (value === null) return null\n if (!isRecord(value)) return \"autoAdvance must be {afterMs, path} or null\"\n if (typeof value.afterMs !== \"number\" || value.afterMs < 0)\n return \"autoAdvance.afterMs must be ms\"\n if (!Array.isArray(value.path) || value.path.some((s) => typeof s !== \"string\")) {\n return \"autoAdvance.path must be a list of vendor statuses\"\n }\n return { afterMs: value.afterMs, path: value.path as string[] }\n}\n\nconst adminRoutes = (runtime: ServiceRuntime<WholescriptsAPI>): AdminRoutes => ({\n \"GET /orders\": ({ namespace }) => json(200, { orders: runtime.instance(namespace).orders() }),\n \"POST /orders/:id/transition\": ({ params, body, namespace }) => {\n if (!isRecord(body) || typeof body.to !== \"string\") {\n return adminError(\n 400,\n 'expected {\"to\": \"Pending|Processing|Complete|Cancelled|Error|\u2026\", \"trackingNumber\"?, \"carrier\"?, \"message\"?}',\n )\n }\n const optional = (key: string) => (typeof body[key] === \"string\" ? { [key]: body[key] } : {})\n const order = runtime.instance(namespace).transition(params.id as string, {\n to: body.to,\n ...optional(\"trackingNumber\"),\n ...optional(\"carrier\"),\n ...optional(\"trackingUrl\"),\n ...optional(\"message\"),\n })\n return order ? json(200, order) : adminError(404, `no order ${params.id}`)\n },\n \"GET /catalog\": ({ namespace }) => json(200, runtime.instance(namespace).state.catalog()),\n \"PUT /catalog\": ({ body, namespace }) => {\n if (\n !isRecord(body) ||\n !Array.isArray(body.products) ||\n !Array.isArray(body.medPaxPills) ||\n !Array.isArray(body.privateLabelCartons)\n ) {\n return adminError(\n 400,\n \"expected {products: [...], medPaxPills: [...], privateLabelCartons: [...]}\",\n )\n }\n return json(200, runtime.instance(namespace).state.replaceCatalog(body as Catalog))\n },\n \"GET /settings\": ({ namespace }) => json(200, runtime.instance(namespace).state.current()),\n \"PUT /settings\": ({ body, namespace }) => {\n if (!isRecord(body)) return adminError(400, \"expected a JSON object\")\n const patch: Partial<Settings> = {}\n if (body.accounts !== undefined) {\n if (!Array.isArray(body.accounts)) return adminError(400, \"accounts: [{username, password}]\")\n patch.accounts = body.accounts.filter(isRecord).map((a) => ({\n username: String(a.username),\n password: String(a.password),\n }))\n }\n if (body.autoAdvance !== undefined) {\n const parsed = parseAutoAdvance(body.autoAdvance)\n if (typeof parsed === \"string\") return adminError(400, parsed)\n patch.autoAdvance = parsed\n }\n return json(200, runtime.instance(namespace).state.update(patch))\n },\n \"POST /tick\": ({ namespace }) => json(200, { applied: runtime.instance(namespace).tick() }),\n})\n\n/**\n * The Wholescripts mock with Mockingbird's full service contract: `/__admin/health`, `/__admin/*`,\n * namespaces by header, by `/__admin/ns/<name>` path prefix, or by Basic username\n * (`PUT /__admin/credentials {\"credentials\": {\"<WHOLESCRIPTS_USERNAME>\": \"<namespace>\"}}`),\n * clock control, fault presets and a request journal. Wholescripts sends no webhooks.\n */\nexport const createRuntime = (options: WholescriptsRuntimeOptions = {}): WholescriptsRuntime => {\n const runtime = createServiceRuntime<WholescriptsAPI>({\n name: WHOLESCRIPTS_NAMESPACE,\n document,\n ...(options.sqlite ? { sqlite: options.sqlite } : {}),\n ...(options.clock ? { clock: options.clock } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.adminPrefix !== undefined ? { adminPrefix: options.adminPrefix } : {}),\n ...(options.adminKey !== undefined ? { adminKey: options.adminKey } : {}),\n ...(options.adminControls !== undefined ? { adminControls: options.adminControls } : {}),\n ...(options.onLog ? { onLog: options.onLog } : {}),\n credential: basicUsername,\n presets: WHOLESCRIPTS_PRESETS,\n create: ({ sqlite, namespace, clock }) =>\n new WholescriptsAPI({\n sqlite,\n namespace,\n now: clock.now,\n ...(options.catalog ? { catalog: options.catalog } : {}),\n ...(options.settings ? { settings: options.settings } : {}),\n }),\n admin: adminRoutes,\n })\n let timer: ReturnType<typeof setInterval> | undefined\n if (options.tickMs !== undefined && options.tickMs > 0) {\n timer = setInterval(() => {\n for (const name of runtime.namespaces()) runtime.instance(name).tick()\n }, options.tickMs)\n ;(timer as { unref?: () => void }).unref?.()\n }\n return Object.assign(runtime, {\n stop: () => {\n if (timer !== undefined) clearInterval(timer)\n },\n })\n}\n", "import type { FetchAPI } from \"@crvouga/mockingbird-core\"\nimport {\n type APIOptions,\n annotateResponse,\n basicAuth,\n bodyIssues,\n bootSqlite,\n createService,\n DroppedConnectionError,\n defineOperations,\n faultEffect,\n HttpError,\n jsonRes,\n type OperationContext,\n opaqueToken,\n type Service,\n} from \"@crvouga/mockingbird-service\"\nimport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nimport type { Hono } from \"hono\"\nimport { type Catalog, orderableSkus, unitPrice } from \"./catalog.js\"\nimport { document, type SupportedOperationId } from \"./generated/openapi.js\"\nimport { type OrderRecord, type Settings, type Tracking, WholescriptsState } from \"./state.js\"\n\nexport type { FetchAPI } from \"@crvouga/mockingbird-core\"\nexport type { SqliteClient } from \"@crvouga/mockingbird-sqlite\"\nexport type {\n Catalog,\n MedPaxDetails,\n MedPaxPill,\n PrivateLabelCarton,\n Product,\n} from \"./catalog.js\"\nexport {\n DEFAULT_CATALOG,\n MEDPAX_BOX_SKU,\n mergeCatalog,\n parseCatalogDocument,\n} from \"./catalog.js\"\nexport type { OperationId, SupportedOperationId } from \"./generated/openapi.js\"\nexport { document, operationIds, supportedOperationIds } from \"./generated/openapi.js\"\nexport type { AutoAdvance, OrderRecord, Settings, Tracking } from \"./state.js\"\n\nexport const WHOLESCRIPTS_NAMESPACE = \"wholescripts\"\n\nexport type WholescriptsAPIOptions = APIOptions & {\n /** The catalog every namespace starts with. Default: {@link DEFAULT_CATALOG}. */\n catalog?: Catalog\n /** Initial per-namespace settings (accounts, auto-advance). */\n settings?: Partial<Settings>\n}\n\n/** ASP.NET Web API's answer to a missing or wrong `Authorization: Basic`. */\nconst UNAUTHORIZED = { Message: \"Authorization has been denied for this request.\" }\n\n/** The Basic username a request carries: how credentials map to namespaces. */\nexport const basicUsername = (request: Request): string | undefined =>\n basicAuth(request)?.username || undefined\n\nconst record = (context: OperationContext): Record<string, unknown> | undefined =>\n context.body.kind === \"json\" &&\n typeof context.body.value === \"object\" &&\n context.body.value !== null &&\n !Array.isArray(context.body.value)\n ? (context.body.value as Record<string, unknown>)\n : undefined\n\nconst round2 = (value: number) => Math.round(value * 100) / 100\n\n/** Canonical casing for the statuses our consumers branch on; anything else is kept verbatim. */\nconst CANONICAL: Record<string, string> = {\n pending: \"Pending\",\n processing: \"Processing\",\n complete: \"Complete\",\n completed: \"Complete\",\n cancelled: \"Cancelled\",\n canceled: \"Cancelled\",\n error: \"Error\",\n}\nexport const canonicalStatus = (to: string): string => CANONICAL[to.trim().toLowerCase()] ?? to\n\nconst statusRow = (order: OrderRecord) => ({\n orderNumber: order.orderNumber,\n orderDate: order.orderDate,\n salesOrder: order.salesOrder,\n status: order.status,\n tracking: order.tracking,\n message: order.message,\n subTotal: order.subTotal,\n shipMethod: order.shipMethod,\n shipCharge: order.shipCharge,\n discount: order.discount,\n tax: order.tax,\n serviceFee: order.serviceFee,\n orderTotal: order.orderTotal,\n})\n\nexport type TransitionInput = {\n to: string\n trackingNumber?: string\n carrier?: string\n trackingUrl?: string\n message?: string\n}\n\nconst trackingUrl = (carrier: string, number: string) =>\n /ups/i.test(carrier)\n ? `https://www.ups.com/track?tracknum=${number}`\n : /usps/i.test(carrier)\n ? `https://tools.usps.com/go/TrackConfirmAction?tLabels=${number}`\n : `https://www.fedex.com/fedextrack/?trknbr=${number}`\n\n/**\n * Stateful mock of the Wholescripts supplement fulfilment API.\n *\n * Orders start `Pending` and move only through admin transitions or auto-advance; nothing is\n * pushed to the app (Wholescripts has no webhooks), so the app sees each change on its next\n * `GET /api/Orders/Status` poll.\n */\nexport class WholescriptsAPI implements FetchAPI {\n readonly app: Hono\n readonly sqlite: SqliteClient\n readonly state: WholescriptsState\n private readonly service: Service\n private readonly now: () => number\n\n constructor(options: WholescriptsAPIOptions = {}) {\n const sqlite = bootSqlite(options.sqlite)\n const namespace = options.namespace ?? WHOLESCRIPTS_NAMESPACE\n this.now = options.now ?? (() => Date.now())\n this.state = new WholescriptsState(sqlite, namespace, {\n catalog: options.catalog,\n settings: options.settings ?? {},\n })\n const handlers = defineOperations<SupportedOperationId>({\n GetPrivateLabelProductList: () => {\n const catalog = this.state.catalog()\n return jsonRes(200, {\n privateLabelProducts: [],\n medPaxPills: catalog.medPaxPills,\n privateLabelCartons: catalog.privateLabelCartons,\n })\n },\n GetProductList: (context) => this.productList(context),\n SubmitOrder: (context) => this.submit(context),\n GetOrderStatus: (context) => this.status(context),\n CancelOrder: (context) => this.cancel(context),\n })\n this.service = createService({\n document,\n handlers,\n sqlite,\n namespace,\n now: this.now,\n notFound: () =>\n jsonRes(404, { Message: \"No HTTP resource was found that matches the request URI.\" }),\n onError: (error) => {\n if (error instanceof HttpError) return error.toResponse()\n throw error\n },\n before: (context) => {\n this.tick()\n const credentials = basicAuth(context.request)\n if (!credentials?.username || !credentials.password) return jsonRes(401, UNAUTHORIZED)\n const accounts = this.state.current().accounts\n if (\n accounts.length > 0 &&\n !accounts.some(\n (a) => a.username === credentials.username && a.password === credentials.password,\n )\n ) {\n return jsonRes(401, UNAUTHORIZED)\n }\n return undefined\n },\n })\n this.app = this.service.app\n this.sqlite = this.service.sqlite\n }\n\n fetch(request: Request): Promise<Response> {\n return this.service.fetch(request)\n }\n\n async reset(): Promise<void> {\n await this.service.reset()\n this.state.ensureSeeded()\n }\n\n private iso(): string {\n return new Date(this.now()).toISOString()\n }\n\n private productList(context: OperationContext): Response {\n const params = context.url.searchParams\n let rows = this.state.catalog().products\n if (params.get(\"instockonly\")?.toLowerCase() === \"true\") {\n rows = rows.filter((p) => p.quantity > 0)\n }\n const search = params.get(\"search\")?.trim().toLowerCase()\n if (search) {\n rows = rows.filter((p) =>\n [p.productName, p.sku, p.medPaxSku, p.brand, p.categories].some((field) =>\n field.toLowerCase().includes(search),\n ),\n )\n }\n const limit = Number(params.get(\"limit\"))\n if (Number.isInteger(limit) && limit > 0) rows = rows.slice(0, limit)\n return jsonRes(200, rows)\n }\n\n private submit(context: OperationContext): Response {\n const rejected = (msg: string) => jsonRes(200, { orderNumber: \"\", success: false, msg })\n if (faultEffect(context.request, \"submit_rejected\") !== undefined) {\n return rejected(\"Payment authorization failed\")\n }\n const body = record(context)\n if (!body) return rejected(\"Invalid order: the request body must be a JSON object\")\n const issues = bodyIssues(context)\n if (issues.length > 0) {\n const first = issues[0]\n return rejected(`Invalid order: ${first?.path || \"body\"} ${first?.message ?? \"is invalid\"}`)\n }\n const items = body.Items as {\n Sku: string\n Quantity: number\n MedPaxPills?: { Sku: string; Quantity: number }[] | null\n }[]\n const catalog = this.state.catalog()\n const skus = orderableSkus(catalog)\n const lines = items.flatMap((item) => [\n { sku: item.Sku, quantity: item.Quantity },\n ...(item.MedPaxPills ?? []).map((pill) => ({ sku: pill.Sku, quantity: pill.Quantity })),\n ])\n const unknown = lines.find((line) => !skus.has(line.sku))\n if (unknown) return rejected(`Invalid SKU: ${unknown.sku}`)\n const subTotal = round2(\n lines.reduce((sum, line) => sum + unitPrice(catalog, line.sku) * line.quantity, 0),\n )\n const shipMethod = String(body.ShippingMethod)\n const shipCharge = /free/i.test(shipMethod) || subTotal === 0 ? 0 : 9.95\n const order: OrderRecord = {\n orderNumber: this.state.nextOrderNumber(),\n orderDate: this.iso(),\n salesOrder: \"\",\n status: \"Pending\",\n tracking: [],\n message: \"\",\n subTotal,\n shipMethod,\n shipCharge,\n discount: 0,\n tax: 0,\n serviceFee: 0,\n orderTotal: round2(subTotal + shipCharge),\n items: lines,\n createdAtMs: this.now(),\n advanced: 0,\n }\n this.state.orders.insert(order.orderNumber, order)\n // The vendor placed the order but the caller never hears back (the scheduler's \"order may have\n // been placed\" timeout branch).\n if (faultEffect(context.request, \"submit_timeout\") !== undefined) {\n throw new DroppedConnectionError()\n }\n return annotateResponse(\n jsonRes(200, {\n orderNumber: order.orderNumber,\n success: true,\n msg: \"Order submitted successfully\",\n }),\n { ids: { orderNumber: order.orderNumber } },\n )\n }\n\n private status(context: OperationContext): Response {\n const ordernum = context.url.searchParams.get(\"ordernum\")?.trim()\n if (!ordernum) return jsonRes(400, { Message: \"The ordernum parameter is required.\" })\n const order = this.state.orders.get(ordernum)\n if (!order || faultEffect(context.request, \"status_empty\") !== undefined) {\n return jsonRes(200, [])\n }\n const row: Record<string, unknown> = statusRow(order)\n if (faultEffect(context.request, \"status_schema_drift\") !== undefined) {\n delete row.salesOrder\n row.orderTotal = String(row.orderTotal)\n }\n return annotateResponse(jsonRes(200, [row]), { ids: { orderNumber: order.orderNumber } })\n }\n\n private cancel(context: OperationContext): Response {\n const body = record(context)\n const orderNumber = typeof body?.OrderNumber === \"string\" ? body.OrderNumber.trim() : \"\"\n if (!orderNumber) return jsonRes(400, { success: false, msg: \"OrderNumber is required\" })\n const order = this.state.orders.get(orderNumber)\n if (!order) return jsonRes(404, { success: false, msg: `Order ${orderNumber} not found` })\n const ids = { orderNumber }\n if (order.status === \"Cancelled\") {\n return annotateResponse(\n jsonRes(200, { success: false, msg: `Order ${orderNumber} is already cancelled` }),\n { ids },\n )\n }\n if (![\"Pending\", \"Processing\"].includes(order.status) || order.tracking.length > 0) {\n return annotateResponse(\n jsonRes(200, {\n success: false,\n msg: `Order ${orderNumber} cannot be cancelled: it is ${order.status}${order.tracking.length > 0 ? \" and has shipped\" : \"\"}`,\n }),\n { ids },\n )\n }\n this.transition(orderNumber, { to: \"Cancelled\", message: \"Cancelled by customer request\" })\n return annotateResponse(\n jsonRes(200, { success: true, msg: `Order ${orderNumber} cancelled` }),\n { ids },\n )\n }\n\n /** Move an order to a vendor status; `Complete` (or a tracking number) adds tracking. */\n transition(orderNumber: string, input: TransitionInput): OrderRecord | undefined {\n const order = this.state.orders.get(orderNumber)\n if (!order) return undefined\n const status = canonicalStatus(input.to)\n let tracking: Tracking[] = order.tracking\n if (input.trackingNumber) {\n const carrier = input.carrier ?? \"UPS\"\n tracking = [\n ...order.tracking.filter((t) => t.trackingNumber !== input.trackingNumber),\n {\n trackingNumber: input.trackingNumber,\n carrier,\n trackingUrl: input.trackingUrl ?? trackingUrl(carrier, input.trackingNumber),\n },\n ]\n } else if (status === \"Complete\" && tracking.length === 0) {\n const number = `1Z${opaqueToken(order.orderNumber, 16).toUpperCase()}`\n const carrier = input.carrier ?? \"UPS\"\n tracking = [{ trackingNumber: number, carrier, trackingUrl: trackingUrl(carrier, number) }]\n }\n const next: OrderRecord = {\n ...order,\n status,\n tracking,\n salesOrder:\n order.salesOrder ||\n (status === \"Processing\" || status === \"Complete\" ? `SO${order.orderNumber}` : \"\"),\n message: input.message ?? (status === \"Error\" ? \"Order could not be processed\" : \"\"),\n }\n this.state.orders.update(orderNumber, next)\n return this.state.orders.get(orderNumber)\n }\n\n /**\n * Apply every auto-advance step that is due on the mock clock. Runs before each vendor\n * request, on `POST /__admin/tick`, and from the served runtime's background ticker.\n */\n tick(): number {\n const plan = this.state.current().autoAdvance\n if (!plan || plan.path.length === 0) return 0\n let applied = 0\n for (const { value: order } of this.state.orders.list({ order: \"oldest\" })) {\n let current = order\n while (current.advanced < plan.path.length) {\n const due = current.createdAtMs + plan.afterMs * (current.advanced + 1)\n if (this.now() < due) break\n const moved = this.transition(current.orderNumber, {\n to: plan.path[current.advanced] as string,\n })\n if (!moved) break\n current = { ...moved, advanced: current.advanced + 1 }\n this.state.orders.update(current.orderNumber, current)\n applied++\n }\n }\n return applied\n }\n\n orders(): OrderRecord[] {\n return this.state.orders.list({ order: \"oldest\" }).map((row) => row.value)\n }\n}\n\nexport type { WholescriptsRuntime, WholescriptsRuntimeOptions } from \"./runtime.js\"\nexport { createRuntime, WHOLESCRIPTS_PRESETS } from \"./runtime.js\"\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA,+CAAC,QAAS,gBAAe,SAAU,gCAA+B,MAAO,oCAAmC,OAAQ,4DAA2D,MAAO,siBAAqiB,OAAQ,MAAK,aAAc,4HAA2H;;;ACAj3B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAAc;AACd,SAAS,mBAAmB,gBAAgB,iBAAiB,qBAAqB;AAC3E,IAAM,kBACX,OAAsD,sBAAkC;AAC1F,IAAM,cACJ,OAAO,2CAAgC,WAAW,yCA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aAAO,QAAQ,WAAW,KAAK,KAAK,QAAQ;AAC1C,cAAM,MAAM,QAAQ,cAAc,KAAK,WAAW,QAAQ,WAAW;AACrE,YAAI,KAAK,IAAI,IAAI,IAAK;AACtB,cAAM,QAAQ,KAAK,WAAW,QAAQ,aAAa;AAAA,UACjD,IAAI,KAAK,KAAK,QAAQ,QAAQ;AAAA,QAChC,CAAC;AACD,YAAI,CAAC,MAAO;AACZ,kBAAU,EAAE,GAAG,OAAO,UAAU,QAAQ,WAAW,EAAE;AACrD,aAAK,MAAM,OAAO,OAAO,QAAQ,aAAa,OAAO;AACrD;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEA,SAAwB;AACtB,WAAO,KAAK,MAAM,OAAO,KAAK,EAAE,OAAO,SAAS,CAAC,EAAE,IAAI,CAAC,QAAQ,IAAI,KAAK;AAAA,EAC3E;AACF;",
|
|
6
|
+
"names": ["document", "isRecord", "createRuntime"]
|
|
7
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
runCli,
|
|
4
|
-
serveCommand,
|
|
5
3
|
serveTarget
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
8
|
-
import "./chunk-2H44NU3T.js";
|
|
4
|
+
} from "./chunk-5IGBFNTP.js";
|
|
5
|
+
import "./chunk-RTRYBGHC.js";
|
|
9
6
|
|
|
10
7
|
// src/cli.ts
|
|
8
|
+
import { runCli, serveCommand } from "@crvouga/mockingbird-runtime/adapter-node";
|
|
11
9
|
var code = await runCli(
|
|
12
10
|
{
|
|
13
11
|
bin: "mockingbird-wholescripts",
|
package/dist/cli.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/cli.ts"],
|
|
4
4
|
"sourcesContent": ["#!/usr/bin/env node\n/// <reference types=\"node\" />\nimport { runCli, serveCommand } from \"@crvouga/mockingbird-adapter-node\"\nimport { serveTarget } from \"./server.js\"\n\nconst code = await runCli(\n {\n bin: \"mockingbird-wholescripts\",\n description: \"stateful Wholescripts supplement fulfilment API mock\",\n commands: { serve: serveCommand(serveTarget) },\n },\n process.argv.slice(2),\n)\nif (code !== 0) process.exitCode = code\n"],
|
|
5
|
-
"mappings": "
|
|
5
|
+
"mappings": ";;;;;;;AAEA,SAAS,QAAQ,oBAAoB;AAGrC,IAAM,OAAO,MAAM;AAAA,EACjB;AAAA,IACE,KAAK;AAAA,IACL,aAAa;AAAA,IACb,UAAU,EAAE,OAAO,aAAa,WAAW,EAAE;AAAA,EAC/C;AAAA,EACA,QAAQ,KAAK,MAAM,CAAC;AACtB;AACA,IAAI,SAAS,EAAG,SAAQ,WAAW;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -113,98 +113,6 @@ interface FetchAPI {
|
|
|
113
113
|
/** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
|
|
114
114
|
type FetchHandler = (request: Request) => Promise<Response>;
|
|
115
115
|
|
|
116
|
-
/** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
|
|
117
|
-
type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
|
|
118
|
-
/** Mutation counters returned by {@link SqliteStatement.run}. */
|
|
119
|
-
type SqliteRunResult$1 = {
|
|
120
|
-
changes: number;
|
|
121
|
-
lastInsertRowid: number | bigint;
|
|
122
|
-
};
|
|
123
|
-
/**
|
|
124
|
-
* Prepared statement bound to a {@link SqliteClient}.
|
|
125
|
-
*
|
|
126
|
-
* Pass bind values as rest arguments on each call (no sticky `bind()`).
|
|
127
|
-
*/
|
|
128
|
-
interface SqliteStatement$1 {
|
|
129
|
-
run(...params: SqliteValue$1[]): SqliteRunResult$1;
|
|
130
|
-
all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
|
|
131
|
-
get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* Sync SQLite client port owned by Mockingbird.
|
|
135
|
-
*
|
|
136
|
-
* Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
|
|
137
|
-
* `bun:sqlite` instances all work when they expose this surface.
|
|
138
|
-
*/
|
|
139
|
-
interface SqliteClient$1 {
|
|
140
|
-
exec(sql: string): void;
|
|
141
|
-
prepare(sql: string): SqliteStatement$1;
|
|
142
|
-
transaction<T>(fn: () => T): T;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** Every stored record carries a monotonically increasing sequence for stable ordering. */
|
|
146
|
-
type Stored<T> = {
|
|
147
|
-
seq: number;
|
|
148
|
-
value: T;
|
|
149
|
-
};
|
|
150
|
-
type ListRecordsOptions<T> = {
|
|
151
|
-
/** Keep only records passing the predicate. */
|
|
152
|
-
where?: (value: T, seq: number) => boolean;
|
|
153
|
-
/** Sort order; default newest first. */
|
|
154
|
-
order?: "newest" | "oldest";
|
|
155
|
-
};
|
|
156
|
-
/**
|
|
157
|
-
* A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
|
|
158
|
-
* sequence, never by id lexicographic order, so list semantics stay stable.
|
|
159
|
-
*/
|
|
160
|
-
declare class Collection<T> {
|
|
161
|
-
private readonly sqlite;
|
|
162
|
-
/** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
|
|
163
|
-
readonly namespace: string;
|
|
164
|
-
/** Table name inside the namespace. Stable across resets of the rows themselves. */
|
|
165
|
-
readonly collectionName: string;
|
|
166
|
-
private readonly statements;
|
|
167
|
-
private prepare;
|
|
168
|
-
constructor(sqlite: SqliteClient$1,
|
|
169
|
-
/** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
|
|
170
|
-
namespace: string,
|
|
171
|
-
/** Table name inside the namespace. Stable across resets of the rows themselves. */
|
|
172
|
-
collectionName: string);
|
|
173
|
-
private bumpCollectionSeq;
|
|
174
|
-
nextSequence(): number;
|
|
175
|
-
get(id: string): T | undefined;
|
|
176
|
-
has(id: string): boolean;
|
|
177
|
-
/** Insert a new record, assigning it the next sequence number. */
|
|
178
|
-
insert(id: string, value: T): Stored<T>;
|
|
179
|
-
/** Replace an existing record's value, keeping its position. */
|
|
180
|
-
update(id: string, value: T): Stored<T> | undefined;
|
|
181
|
-
delete(id: string): boolean;
|
|
182
|
-
/** How many records the collection holds, without reading them. */
|
|
183
|
-
count(): number;
|
|
184
|
-
list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
|
|
185
|
-
id: string;
|
|
186
|
-
}>;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
|
|
191
|
-
* which derives the base from the wall clock when the runtime is created.
|
|
192
|
-
*/
|
|
193
|
-
type IdBase = number | string;
|
|
194
|
-
|
|
195
|
-
/** Options every provider constructor accepts. */
|
|
196
|
-
type APIOptions = {
|
|
197
|
-
/** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
|
|
198
|
-
sqlite?: SqliteClient$1;
|
|
199
|
-
/** Clock used for `created`-style fields. Default `Date.now`. */
|
|
200
|
-
now?: () => number;
|
|
201
|
-
/**
|
|
202
|
-
* Storage namespace for this instance's records. Instances sharing one SQLite
|
|
203
|
-
* client stay isolated when their namespaces differ. Defaults to the service name.
|
|
204
|
-
*/
|
|
205
|
-
namespace?: string;
|
|
206
|
-
};
|
|
207
|
-
|
|
208
116
|
/**
|
|
209
117
|
* The single source of time for a service.
|
|
210
118
|
*
|
|
@@ -235,6 +143,11 @@ type Clock = {
|
|
|
235
143
|
state(): ClockState;
|
|
236
144
|
};
|
|
237
145
|
|
|
146
|
+
type UpstreamState = {
|
|
147
|
+
mode: "emulated" | "forward";
|
|
148
|
+
baseUrl: string;
|
|
149
|
+
};
|
|
150
|
+
|
|
238
151
|
/**
|
|
239
152
|
* Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
|
|
240
153
|
* request a percentage fault hits — is reproducible from a seed.
|
|
@@ -511,6 +424,7 @@ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
|
|
|
511
424
|
* `records` are required, so a hand-written seed file is a valid snapshot.
|
|
512
425
|
*/
|
|
513
426
|
type SnapshotDocument = {
|
|
427
|
+
upstream?: UpstreamState;
|
|
514
428
|
format: typeof SNAPSHOT_FORMAT;
|
|
515
429
|
/** The service that wrote it. A snapshot is rejected by any other service. */
|
|
516
430
|
service?: string;
|
|
@@ -584,6 +498,7 @@ type LatencyState = LatencyRule & {
|
|
|
584
498
|
};
|
|
585
499
|
/** What {@link controlHeaders} turns into request headers. */
|
|
586
500
|
type ControlHeaderInput = {
|
|
501
|
+
upstream?: "emulated" | "forward";
|
|
587
502
|
namespace?: string;
|
|
588
503
|
adminKey?: string;
|
|
589
504
|
branch?: string;
|
|
@@ -601,6 +516,48 @@ type ControlHeaderInput = {
|
|
|
601
516
|
snapshot?: string;
|
|
602
517
|
};
|
|
603
518
|
|
|
519
|
+
/** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
|
|
520
|
+
type SqliteValue$1 = null | number | bigint | string | Uint8Array | boolean;
|
|
521
|
+
/** Mutation counters returned by {@link SqliteStatement.run}. */
|
|
522
|
+
type SqliteRunResult$1 = {
|
|
523
|
+
changes: number;
|
|
524
|
+
lastInsertRowid: number | bigint;
|
|
525
|
+
};
|
|
526
|
+
/**
|
|
527
|
+
* Prepared statement bound to a {@link SqliteClient}.
|
|
528
|
+
*
|
|
529
|
+
* Pass bind values as rest arguments on each call (no sticky `bind()`).
|
|
530
|
+
*/
|
|
531
|
+
interface SqliteStatement$1 {
|
|
532
|
+
run(...params: SqliteValue$1[]): SqliteRunResult$1;
|
|
533
|
+
all<T = Record<string, unknown>>(...params: SqliteValue$1[]): T[];
|
|
534
|
+
get<T = Record<string, unknown>>(...params: SqliteValue$1[]): T | undefined;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Sync SQLite client port owned by Mockingbird.
|
|
538
|
+
*
|
|
539
|
+
* Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
|
|
540
|
+
* `bun:sqlite` instances all work when they expose this surface.
|
|
541
|
+
*/
|
|
542
|
+
interface SqliteClient$1 {
|
|
543
|
+
exec(sql: string): void;
|
|
544
|
+
prepare(sql: string): SqliteStatement$1;
|
|
545
|
+
transaction<T>(fn: () => T): T;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** Options every provider constructor accepts. */
|
|
549
|
+
type APIOptions = {
|
|
550
|
+
/** Sync SQLite client. Defaults to `@crvouga/mockingbird-service-sqlite`. */
|
|
551
|
+
sqlite?: SqliteClient$1;
|
|
552
|
+
/** Clock used for `created`-style fields. Default `Date.now`. */
|
|
553
|
+
now?: () => number;
|
|
554
|
+
/**
|
|
555
|
+
* Storage namespace for this instance's records. Instances sharing one SQLite
|
|
556
|
+
* client stay isolated when their namespaces differ. Defaults to the service name.
|
|
557
|
+
*/
|
|
558
|
+
namespace?: string;
|
|
559
|
+
};
|
|
560
|
+
|
|
604
561
|
/**
|
|
605
562
|
* One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
|
|
606
563
|
* `kind` is `media_type` when the body is present but its media type is not one the operation
|
|
@@ -627,6 +584,7 @@ type RejectedRequest = {
|
|
|
627
584
|
};
|
|
628
585
|
/** One handled request, as the structured log sees it. */
|
|
629
586
|
type RequestLog = {
|
|
587
|
+
upstream?: boolean;
|
|
630
588
|
service: string;
|
|
631
589
|
namespace: string;
|
|
632
590
|
operationId: string | undefined;
|
|
@@ -761,8 +719,6 @@ type CredentialRegistry = {
|
|
|
761
719
|
}[];
|
|
762
720
|
};
|
|
763
721
|
|
|
764
|
-
type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
|
|
765
|
-
|
|
766
722
|
/**
|
|
767
723
|
* A point-in-time copy of everything a service namespace holds.
|
|
768
724
|
*
|
|
@@ -785,6 +741,50 @@ type NamespaceSnapshot = {
|
|
|
785
741
|
}[];
|
|
786
742
|
};
|
|
787
743
|
|
|
744
|
+
/** Every stored record carries a monotonically increasing sequence for stable ordering. */
|
|
745
|
+
type Stored<T> = {
|
|
746
|
+
seq: number;
|
|
747
|
+
value: T;
|
|
748
|
+
};
|
|
749
|
+
type ListRecordsOptions<T> = {
|
|
750
|
+
/** Keep only records passing the predicate. */
|
|
751
|
+
where?: (value: T, seq: number) => boolean;
|
|
752
|
+
/** Sort order; default newest first. */
|
|
753
|
+
order?: "newest" | "oldest";
|
|
754
|
+
};
|
|
755
|
+
/**
|
|
756
|
+
* A SQLite-backed table of JSON records addressed by id. Ordering is by insertion
|
|
757
|
+
* sequence, never by id lexicographic order, so list semantics stay stable.
|
|
758
|
+
*/
|
|
759
|
+
declare class Collection<T> {
|
|
760
|
+
private readonly sqlite;
|
|
761
|
+
/** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
|
|
762
|
+
readonly namespace: string;
|
|
763
|
+
/** Table name inside the namespace. Stable across resets of the rows themselves. */
|
|
764
|
+
readonly collectionName: string;
|
|
765
|
+
private readonly statements;
|
|
766
|
+
private prepare;
|
|
767
|
+
constructor(sqlite: SqliteClient$1,
|
|
768
|
+
/** Storage namespace. Admin introspection uses this to ignore another namespace's tables. */
|
|
769
|
+
namespace: string,
|
|
770
|
+
/** Table name inside the namespace. Stable across resets of the rows themselves. */
|
|
771
|
+
collectionName: string);
|
|
772
|
+
private bumpCollectionSeq;
|
|
773
|
+
nextSequence(): number;
|
|
774
|
+
get(id: string): T | undefined;
|
|
775
|
+
has(id: string): boolean;
|
|
776
|
+
/** Insert a new record, assigning it the next sequence number. */
|
|
777
|
+
insert(id: string, value: T): Stored<T>;
|
|
778
|
+
/** Replace an existing record's value, keeping its position. */
|
|
779
|
+
update(id: string, value: T): Stored<T> | undefined;
|
|
780
|
+
delete(id: string): boolean;
|
|
781
|
+
/** How many records the collection holds, without reading them. */
|
|
782
|
+
count(): number;
|
|
783
|
+
list(options?: ListRecordsOptions<T>): Array<Stored<T> & {
|
|
784
|
+
id: string;
|
|
785
|
+
}>;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
788
|
declare const STATE_FIELD_KINDS: readonly ["string", "number", "boolean", "null", "object", "array", "unknown"];
|
|
789
789
|
type StateFieldKind = (typeof STATE_FIELD_KINDS)[number];
|
|
790
790
|
/** JSON-safe annotations a bespoke admin UI may read. The default UI shows them as text. */
|
|
@@ -815,6 +815,14 @@ type StateView = {
|
|
|
815
815
|
collections: StateCollectionView[];
|
|
816
816
|
};
|
|
817
817
|
|
|
818
|
+
/**
|
|
819
|
+
* What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
|
|
820
|
+
* which derives the base from the wall clock when the runtime is created.
|
|
821
|
+
*/
|
|
822
|
+
type IdBase = number | string;
|
|
823
|
+
|
|
824
|
+
type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
|
|
825
|
+
|
|
818
826
|
type WebhookEndpoint = {
|
|
819
827
|
/** Stable id; generated when omitted. */
|
|
820
828
|
id?: string;
|
package/dist/index.js
CHANGED
package/dist/server.d.ts
CHANGED
|
@@ -105,41 +105,6 @@ interface FetchAPI {
|
|
|
105
105
|
/** A bare function form of {@link FetchAPI}, compatible with `Bun.serve`, workerd, and Deno. */
|
|
106
106
|
type FetchHandler = (request: Request) => Promise<Response>;
|
|
107
107
|
|
|
108
|
-
/** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
|
|
109
|
-
type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
|
|
110
|
-
/** Mutation counters returned by {@link SqliteStatement.run}. */
|
|
111
|
-
type SqliteRunResult = {
|
|
112
|
-
changes: number;
|
|
113
|
-
lastInsertRowid: number | bigint;
|
|
114
|
-
};
|
|
115
|
-
/**
|
|
116
|
-
* Prepared statement bound to a {@link SqliteClient}.
|
|
117
|
-
*
|
|
118
|
-
* Pass bind values as rest arguments on each call (no sticky `bind()`).
|
|
119
|
-
*/
|
|
120
|
-
interface SqliteStatement {
|
|
121
|
-
run(...params: SqliteValue[]): SqliteRunResult;
|
|
122
|
-
all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
|
|
123
|
-
get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* Sync SQLite client port owned by Mockingbird.
|
|
127
|
-
*
|
|
128
|
-
* Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
|
|
129
|
-
* `bun:sqlite` instances all work when they expose this surface.
|
|
130
|
-
*/
|
|
131
|
-
interface SqliteClient {
|
|
132
|
-
exec(sql: string): void;
|
|
133
|
-
prepare(sql: string): SqliteStatement;
|
|
134
|
-
transaction<T>(fn: () => T): T;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
|
|
139
|
-
* which derives the base from the wall clock when the runtime is created.
|
|
140
|
-
*/
|
|
141
|
-
type IdBase = number | string;
|
|
142
|
-
|
|
143
108
|
/**
|
|
144
109
|
* The single source of time for a service.
|
|
145
110
|
*
|
|
@@ -170,6 +135,11 @@ type Clock = {
|
|
|
170
135
|
state(): ClockState;
|
|
171
136
|
};
|
|
172
137
|
|
|
138
|
+
type UpstreamState = {
|
|
139
|
+
mode: "emulated" | "forward";
|
|
140
|
+
baseUrl: string;
|
|
141
|
+
};
|
|
142
|
+
|
|
173
143
|
/**
|
|
174
144
|
* Seeded pseudo-random numbers, so anything a mock invents — ids, jitter, which
|
|
175
145
|
* request a percentage fault hits — is reproducible from a seed.
|
|
@@ -433,6 +403,7 @@ declare const SNAPSHOT_FORMAT = "mockingbird.snapshot/v1";
|
|
|
433
403
|
* `records` are required, so a hand-written seed file is a valid snapshot.
|
|
434
404
|
*/
|
|
435
405
|
type SnapshotDocument = {
|
|
406
|
+
upstream?: UpstreamState;
|
|
436
407
|
format: typeof SNAPSHOT_FORMAT;
|
|
437
408
|
/** The service that wrote it. A snapshot is rejected by any other service. */
|
|
438
409
|
service?: string;
|
|
@@ -506,6 +477,7 @@ type LatencyState = LatencyRule & {
|
|
|
506
477
|
};
|
|
507
478
|
/** What {@link controlHeaders} turns into request headers. */
|
|
508
479
|
type ControlHeaderInput = {
|
|
480
|
+
upstream?: "emulated" | "forward";
|
|
509
481
|
namespace?: string;
|
|
510
482
|
adminKey?: string;
|
|
511
483
|
branch?: string;
|
|
@@ -523,6 +495,35 @@ type ControlHeaderInput = {
|
|
|
523
495
|
snapshot?: string;
|
|
524
496
|
};
|
|
525
497
|
|
|
498
|
+
/** Bind values accepted by Mockingbird's SQLite port (matches sqlite-mem / better-sqlite3). */
|
|
499
|
+
type SqliteValue = null | number | bigint | string | Uint8Array | boolean;
|
|
500
|
+
/** Mutation counters returned by {@link SqliteStatement.run}. */
|
|
501
|
+
type SqliteRunResult = {
|
|
502
|
+
changes: number;
|
|
503
|
+
lastInsertRowid: number | bigint;
|
|
504
|
+
};
|
|
505
|
+
/**
|
|
506
|
+
* Prepared statement bound to a {@link SqliteClient}.
|
|
507
|
+
*
|
|
508
|
+
* Pass bind values as rest arguments on each call (no sticky `bind()`).
|
|
509
|
+
*/
|
|
510
|
+
interface SqliteStatement {
|
|
511
|
+
run(...params: SqliteValue[]): SqliteRunResult;
|
|
512
|
+
all<T = Record<string, unknown>>(...params: SqliteValue[]): T[];
|
|
513
|
+
get<T = Record<string, unknown>>(...params: SqliteValue[]): T | undefined;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Sync SQLite client port owned by Mockingbird.
|
|
517
|
+
*
|
|
518
|
+
* Duck-typed so `@crvouga/mockingbird-service-sqlite` `Database`, better-sqlite3, and wrapped
|
|
519
|
+
* `bun:sqlite` instances all work when they expose this surface.
|
|
520
|
+
*/
|
|
521
|
+
interface SqliteClient {
|
|
522
|
+
exec(sql: string): void;
|
|
523
|
+
prepare(sql: string): SqliteStatement;
|
|
524
|
+
transaction<T>(fn: () => T): T;
|
|
525
|
+
}
|
|
526
|
+
|
|
526
527
|
/**
|
|
527
528
|
* One problem with a request body, at a dotted path (`patient.address.city`, `items.0.sku`).
|
|
528
529
|
* `kind` is `media_type` when the body is present but its media type is not one the operation
|
|
@@ -549,6 +550,7 @@ type RejectedRequest = {
|
|
|
549
550
|
};
|
|
550
551
|
/** One handled request, as the structured log sees it. */
|
|
551
552
|
type RequestLog = {
|
|
553
|
+
upstream?: boolean;
|
|
552
554
|
service: string;
|
|
553
555
|
namespace: string;
|
|
554
556
|
operationId: string | undefined;
|
|
@@ -683,8 +685,6 @@ type CredentialRegistry = {
|
|
|
683
685
|
}[];
|
|
684
686
|
};
|
|
685
687
|
|
|
686
|
-
type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
|
|
687
|
-
|
|
688
688
|
/**
|
|
689
689
|
* A point-in-time copy of everything a service namespace holds.
|
|
690
690
|
*
|
|
@@ -737,6 +737,14 @@ type StateView = {
|
|
|
737
737
|
collections: StateCollectionView[];
|
|
738
738
|
};
|
|
739
739
|
|
|
740
|
+
/**
|
|
741
|
+
* What names an id base: a non-negative safe integer (or its decimal string) or `"boot"`,
|
|
742
|
+
* which derives the base from the wall clock when the runtime is created.
|
|
743
|
+
*/
|
|
744
|
+
type IdBase = number | string;
|
|
745
|
+
|
|
746
|
+
type OwnedTransport = (request: Request, namespace: string, send: typeof fetch) => Promise<Response>;
|
|
747
|
+
|
|
740
748
|
type WebhookEndpoint = {
|
|
741
749
|
/** Stable id; generated when omitted. */
|
|
742
750
|
id?: string;
|
package/dist/server.js
CHANGED
|
@@ -3,9 +3,8 @@ import {
|
|
|
3
3
|
createServer,
|
|
4
4
|
loadCatalogFile,
|
|
5
5
|
serveTarget
|
|
6
|
-
} from "./chunk-
|
|
7
|
-
import "./chunk-
|
|
8
|
-
import "./chunk-2H44NU3T.js";
|
|
6
|
+
} from "./chunk-5IGBFNTP.js";
|
|
7
|
+
import "./chunk-RTRYBGHC.js";
|
|
9
8
|
export {
|
|
10
9
|
DEFAULT_PORT,
|
|
11
10
|
createServer,
|