@gusto/baerly-storage 0.1.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 (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,104 @@
1
+ import { t as parseBucketUri } from "./bucket-uri-BrDEYvzy.js";
2
+ import { n as loadCollectionIndexes } from "./config-Bsg8wgwo.js";
3
+ import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
+ import { t as rebuildIndex } from "./rebuild-index-C5gTXryd.js";
5
+ import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
6
+ //#region src/admin/rebuild-index.ts
7
+ /** citty arg shape. Kebab-case so --help and parsed-object keys line up. */
8
+ const REBUILD_INDEX_ARGS = {
9
+ bucket: {
10
+ type: "string",
11
+ required: true,
12
+ description: "Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)",
13
+ valueHint: "bucket-uri"
14
+ },
15
+ app: {
16
+ type: "string",
17
+ required: false,
18
+ description: "Application name segment (defaults to baerly.config.ts).",
19
+ valueHint: "app"
20
+ },
21
+ tenant: {
22
+ type: "string",
23
+ required: false,
24
+ description: "Tenant name segment (defaults to baerly.config.ts).",
25
+ valueHint: "tenant"
26
+ },
27
+ collection: {
28
+ type: "string",
29
+ required: true,
30
+ description: "Collection name",
31
+ valueHint: "name"
32
+ },
33
+ index: {
34
+ type: "string",
35
+ required: true,
36
+ description: "Index name (e.g. by_status)",
37
+ valueHint: "name"
38
+ },
39
+ on: {
40
+ type: "string",
41
+ required: false,
42
+ description: "Field the index projects on. Required unless --config supplies it.",
43
+ valueHint: "field"
44
+ },
45
+ config: {
46
+ type: "string",
47
+ required: false,
48
+ description: "Path to baerly.config.{js,mjs,json} — used to resolve the index's `on` field.",
49
+ valueHint: "path"
50
+ },
51
+ json: {
52
+ type: "boolean",
53
+ description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
54
+ },
55
+ verbose: {
56
+ type: "boolean",
57
+ description: "Emit a one-line summary to stdout in addition to the JSON envelope."
58
+ }
59
+ };
60
+ /** Resolve the `on` field of a single named index from the config file. */
61
+ const onFieldFromConfig = async (configPath, collection, indexName) => {
62
+ const def = (await loadCollectionIndexes(configPath, collection, "baerly admin rebuild-index")).find((d) => d.name === indexName);
63
+ if (def === void 0) throw new BaerlyError("InvalidConfig", `baerly admin rebuild-index: config has no index ${JSON.stringify(indexName)} on collection ${JSON.stringify(collection)}`);
64
+ return def.on;
65
+ };
66
+ const bundle = defineBaerlySubcommand({
67
+ name: "admin.rebuild-index",
68
+ meta: { description: "Idempotent reconciliation of one secondary index." },
69
+ args: REBUILD_INDEX_ARGS,
70
+ handler: async (args, ctx) => {
71
+ const bucket = await parseBucketUri(args.bucket);
72
+ const on = args.config !== void 0 && args.config.length > 0 ? await onFieldFromConfig(args.config, args.collection, args.index) : args.on;
73
+ if (on === void 0 || on.length === 0) throw new BaerlyError("InvalidConfig", "baerly admin rebuild-index: --on=<field> (or --config=<path>) is required");
74
+ const def = {
75
+ name: args.index,
76
+ on
77
+ };
78
+ const { app, tenant } = await ctx.resolveAppTenant({
79
+ app: args.app,
80
+ tenant: args.tenant
81
+ });
82
+ const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
83
+ const result = await rebuildIndex(bucket.storage, currentJsonKey, def);
84
+ emitSuccess({
85
+ command: "admin.rebuild-index",
86
+ status: "ok",
87
+ added: result.added,
88
+ removed: result.removed,
89
+ kept: result.kept
90
+ });
91
+ if (args.verbose === true) process.stdout.write(`rebuild-index: added=${result.added} removed=${result.removed} kept=${result.kept}\n`);
92
+ return 0;
93
+ }
94
+ });
95
+ /**
96
+ * citty `defineCommand` block for `baerly admin rebuild-index`.
97
+ * Mounted on the `admin` subcommand tree in `baerly.ts`.
98
+ */
99
+ const rebuildIndexCmd = bundle.cmd;
100
+ bundle.run;
101
+ //#endregion
102
+ export { rebuildIndexCmd };
103
+
104
+ //# sourceMappingURL=rebuild-index-DwXM0WfA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rebuild-index-DwXM0WfA.js","names":[],"sources":["../packages/cli/src/admin/rebuild-index.ts"],"sourcesContent":["/**\n * `baerly admin rebuild-index` — idempotent reconciliation for one\n * secondary index. Walks the live `(snapshot, log)` of the named\n * collection, computes the expected index-key set under the named\n * index's definition, then PUTs missing keys and DELETEs orphans.\n *\n * Cost shape: `1 GET (current.json) + 1 GET (snapshot, if any) + N\n * GETs (live tail) + 1 LIST (the index prefix) + K PUTs + L DELETEs`.\n *\n * Exit codes (standard CLI shape):\n * - `0` — success (envelope on stdout in --json mode).\n * - `1` — user error (InvalidConfig: bad bucket URI, missing\n * args, unparseable config).\n * - `2` — storage error (NetworkError, AccessDenied, anything\n * non-BaerlyError).\n * - `3` — protocol invariant (Conflict, Internal, InvalidResponse).\n *\n * Idempotent — re-running on a healthy index is `{ removed: 0,\n * added: 0 }`; re-running after a crashed mid-commit reconciles\n * toward the live current.json view.\n *\n * Args:\n * --bucket Bucket URI (s3://..., file:///<abs>, memory://...).\n * --app Application name segment (defaults to baerly.config.ts).\n * --tenant Tenant name segment (defaults to baerly.config.ts).\n * --collection Collection name.\n * --index Index name (e.g. \"by_status\").\n * --on Field the index projects on (string today; matches\n * the IndexDefinition shape declared in baerly.config.ts).\n * --config Path to a baerly.config.{js,mjs,json}. Loaded with\n * dynamic import; the matching collection.indexes[]\n * definition is used. Mutually-exclusive with --on\n * (config takes precedence). `.ts` configs are not\n * supported today — point at the compiled output.\n *\n * The reconciliation logic itself lives in `@baerly/server`'s\n * `rebuildIndex`; this command is a thin URI + arg-parsing wrapper.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type IndexDefinition } from \"@baerly/protocol\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { loadCollectionIndexes } from \"../config.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\n/** citty arg shape. Kebab-case so --help and parsed-object keys line up. */\nconst REBUILD_INDEX_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name\",\n valueHint: \"name\",\n },\n index: {\n type: \"string\",\n required: true,\n description: \"Index name (e.g. by_status)\",\n valueHint: \"name\",\n },\n on: {\n type: \"string\",\n required: false,\n description: \"Field the index projects on. Required unless --config supplies it.\",\n valueHint: \"field\",\n },\n config: {\n type: \"string\",\n required: false,\n description: \"Path to baerly.config.{js,mjs,json} — used to resolve the index's `on` field.\",\n valueHint: \"path\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n verbose: {\n type: \"boolean\",\n description: \"Emit a one-line summary to stdout in addition to the JSON envelope.\",\n },\n} as const satisfies ArgsDef;\n\n/** Resolve the `on` field of a single named index from the config file. */\nconst onFieldFromConfig = async (\n configPath: string,\n collection: string,\n indexName: string,\n): Promise<string | readonly string[]> => {\n const indexes = await loadCollectionIndexes(configPath, collection, \"baerly admin rebuild-index\");\n const def = indexes.find((d) => d.name === indexName);\n if (def === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin rebuild-index: config has no index ${JSON.stringify(indexName)} on collection ${JSON.stringify(collection)}`,\n );\n }\n return def.on;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.rebuild-index\",\n meta: {\n description: \"Idempotent reconciliation of one secondary index.\",\n },\n args: REBUILD_INDEX_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const on =\n args.config !== undefined && args.config.length > 0\n ? await onFieldFromConfig(args.config, args.collection, args.index)\n : args.on;\n if (on === undefined || on.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin rebuild-index: --on=<field> (or --config=<path>) is required\",\n );\n }\n const def: IndexDefinition = { name: args.index, on };\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const result = await rebuildIndex(bucket.storage, currentJsonKey, def);\n emitSuccess({\n command: \"admin.rebuild-index\",\n status: \"ok\",\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n });\n if (args.verbose === true) {\n process.stdout.write(\n `rebuild-index: added=${result.added} removed=${result.removed} kept=${result.kept}\\n`,\n );\n }\n return 0;\n },\n});\n\n/**\n * citty `defineCommand` block for `baerly admin rebuild-index`.\n * Mounted on the `admin` subcommand tree in `baerly.ts`.\n */\nexport const rebuildIndexCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n *\n * @param argv Args AFTER the `admin rebuild-index` subcommand.\n */\nexport const runRebuildIndex = bundle.run;\n"],"mappings":";;;;;;;AAgDA,MAAM,qBAAqB;CACzB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,OAAO;EACL,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,IAAI;EACF,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,SAAS;EACP,MAAM;EACN,aAAa;CACf;AACF;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erlyError } from "./errors-DOdL95kK.js";
2
+ //#region packages/client/src/internal/context.ts
3
+ /**
4
+ * Symbol-keyed slot on every `BaerlyClient` carrying the internal
5
+ * `RequestContext`. Lets internals (e.g. the React
6
+ * `subscription-pool`) reach the same fetcher / headers resolution
7
+ * the typed API uses, without widening the public `BaerlyClient`
8
+ * surface.
9
+ *
10
+ * Symbol is module-scoped — users cannot import it from package
11
+ * internals, so the slot is invisible outside this package.
12
+ */
13
+ const CLIENT_CONTEXT = Symbol("baerly.client.context");
14
+ /**
15
+ * Returns the internal `RequestContext` stashed on `client` by
16
+ * `createBaerlyClient`. Throws if called with a client not produced
17
+ * by `createBaerlyClient` (e.g. a test stub) — that is the right
18
+ * signal for callers, who in production have no other way to obtain
19
+ * a `BaerlyClient` instance.
20
+ */
21
+ const getClientContext = (client) => {
22
+ const ctx = client[CLIENT_CONTEXT];
23
+ if (ctx === void 0) throw new Error("getClientContext: client was not produced by createBaerlyClient (missing internal context slot)");
24
+ return ctx;
25
+ };
26
+ //#endregion
27
+ //#region packages/client/src/request.ts
28
+ /**
29
+ * Issue one HTTP request and unwrap the response per the locked
30
+ * status-code policy in `packages/server/src/contract.ts:73-89`:
31
+ *
32
+ * - 204 → `undefined as T` (DELETE success — no body).
33
+ * - 201 → raw parsed body as T (POST insert success — body `{ _id }`).
34
+ * - 4xx / 5xx → parse `HttpErrorEnvelope` and throw
35
+ * {@link BaerlyError} with `status` set to the wire HTTP code.
36
+ * Non-JSON error bodies synthesize an `Internal` code so consumers
37
+ * still get a structured throw.
38
+ * - 200 on non-`GET` (PATCH, future mutations) → raw parsed body
39
+ * as T (e.g. `{ modified }`).
40
+ * - 200 on `GET /v1/since` → raw `SinceResponse` as T (no `data` unwrap).
41
+ * - 200 on any other `GET` → `HttpOkEnvelope<T>.data`.
42
+ */
43
+ const request = async (ctx, opts) => {
44
+ const headers = new Headers(ctx.headers);
45
+ if (opts.body !== void 0) headers.set("content-type", "application/json");
46
+ const init = {
47
+ method: opts.method,
48
+ headers,
49
+ body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body),
50
+ signal: opts.signal
51
+ };
52
+ const req = new Request(`${ctx.baseUrl}${opts.path}`, init);
53
+ const res = await ctx.fetch(req);
54
+ if (res.status === 204) return;
55
+ if (res.status === 201) return await res.json();
56
+ if (!res.ok) {
57
+ let envelope;
58
+ try {
59
+ envelope = await res.json();
60
+ } catch {}
61
+ throw new BaerlyError(envelope?.error?.code ?? "Internal", envelope?.error?.message ?? `HTTP ${res.status}`, void 0, void 0, res.status);
62
+ }
63
+ const body = await res.json();
64
+ if (opts.method !== "GET") return body;
65
+ if (opts.path.startsWith("/v1/since")) return body;
66
+ if (typeof body !== "object" || body === null || !("data" in body)) throw new BaerlyError("InvalidResponse", `Response to ${opts.method} ${opts.path} missing 'data' field`, void 0, void 0, res.status);
67
+ return body.data;
68
+ };
69
+ //#endregion
70
+ export { CLIENT_CONTEXT as n, getClientContext as r, request as t };
71
+
72
+ //# sourceMappingURL=request-BEF_OvMh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-BEF_OvMh.js","names":[],"sources":["../packages/client/src/internal/context.ts","../packages/client/src/request.ts"],"sourcesContent":["import type { BaerlyClient } from \"../client.ts\";\nimport type { RequestContext } from \"../request.ts\";\n\n/**\n * Symbol-keyed slot on every `BaerlyClient` carrying the internal\n * `RequestContext`. Lets internals (e.g. the React\n * `subscription-pool`) reach the same fetcher / headers resolution\n * the typed API uses, without widening the public `BaerlyClient`\n * surface.\n *\n * Symbol is module-scoped — users cannot import it from package\n * internals, so the slot is invisible outside this package.\n */\nexport const CLIENT_CONTEXT: unique symbol = Symbol(\"baerly.client.context\");\n\ninterface ClientWithContext {\n readonly [CLIENT_CONTEXT]: RequestContext;\n}\n\n/**\n * Returns the internal `RequestContext` stashed on `client` by\n * `createBaerlyClient`. Throws if called with a client not produced\n * by `createBaerlyClient` (e.g. a test stub) — that is the right\n * signal for callers, who in production have no other way to obtain\n * a `BaerlyClient` instance.\n */\nexport const getClientContext = (client: BaerlyClient): RequestContext => {\n const ctx = (client as unknown as Partial<ClientWithContext>)[CLIENT_CONTEXT];\n if (ctx === undefined) {\n throw new Error(\n \"getClientContext: client was not produced by createBaerlyClient (missing internal context slot)\",\n );\n }\n return ctx;\n};\n","import { BaerlyError, type BaerlyErrorCode } from \"@baerly/protocol\";\nimport type { HttpErrorEnvelope, HttpOkEnvelope } from \"./contract.ts\";\n\n/**\n * Pluggable fetch implementation. Defaults to `globalThis.fetch`;\n * tests override with a {@link MockFetch}.\n */\nexport type Fetcher = (req: Request) => Promise<Response>;\n\nexport interface RequestOptions {\n readonly method: \"GET\" | \"POST\" | \"PATCH\" | \"PUT\" | \"DELETE\";\n readonly path: string;\n readonly body?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Internal carrier passed to every {@link request} call. Built once\n * by `createBaerlyClient` from `BaerlyClientOptions`.\n *\n * `headers` is the shared template; callers MUST clone before\n * mutating (each request adds `content-type`).\n */\nexport interface RequestContext {\n readonly baseUrl: string;\n readonly fetch: Fetcher;\n readonly headers: Headers;\n}\n\n/**\n * Issue one HTTP request and unwrap the response per the locked\n * status-code policy in `packages/server/src/contract.ts:73-89`:\n *\n * - 204 → `undefined as T` (DELETE success — no body).\n * - 201 → raw parsed body as T (POST insert success — body `{ _id }`).\n * - 4xx / 5xx → parse `HttpErrorEnvelope` and throw\n * {@link BaerlyError} with `status` set to the wire HTTP code.\n * Non-JSON error bodies synthesize an `Internal` code so consumers\n * still get a structured throw.\n * - 200 on non-`GET` (PATCH, future mutations) → raw parsed body\n * as T (e.g. `{ modified }`).\n * - 200 on `GET /v1/since` → raw `SinceResponse` as T (no `data` unwrap).\n * - 200 on any other `GET` → `HttpOkEnvelope<T>.data`.\n */\nexport const request = async <T>(ctx: RequestContext, opts: RequestOptions): Promise<T> => {\n const headers = new Headers(ctx.headers);\n if (opts.body !== undefined) {\n headers.set(\"content-type\", \"application/json\");\n }\n const init: RequestInit = {\n method: opts.method,\n headers,\n body: opts.body === undefined ? undefined : JSON.stringify(opts.body),\n signal: opts.signal,\n };\n const req = new Request(`${ctx.baseUrl}${opts.path}`, init);\n const res = await ctx.fetch(req);\n\n // 204 No Content — never a body; cast the \"no value\" to T. The\n // only caller (`delete`) types T = undefined so this is safe.\n if (res.status === 204) {\n return undefined as T;\n }\n\n // 201 Created — body is `{ _id }`, not `HttpOkEnvelope`. The only\n // caller (`insert`) types T = `{ _id }` so we return the parsed\n // body raw.\n if (res.status === 201) {\n return (await res.json()) as T;\n }\n\n // 4xx / 5xx — `HttpErrorEnvelope`. Parse + throw.\n if (!res.ok) {\n let envelope: HttpErrorEnvelope | undefined;\n try {\n envelope = (await res.json()) as HttpErrorEnvelope;\n } catch {\n // Non-JSON body (e.g. an upstream proxy 502). Synthesize an\n // Internal error so consumers still get a structured throw.\n }\n const code: BaerlyErrorCode = envelope?.error?.code ?? \"Internal\";\n const message = envelope?.error?.message ?? `HTTP ${res.status}`;\n throw new BaerlyError(code, message, undefined, undefined, res.status);\n }\n\n // 200 — only GET reads ship `HttpOkEnvelope<T>`. PATCH (and any\n // future non-GET mutation that hits 200) ships its body raw. GET\n // /v1/since also ships raw (`SinceResponse`).\n const body = (await res.json()) as unknown;\n if (opts.method !== \"GET\") {\n return body as T;\n }\n if (opts.path.startsWith(\"/v1/since\")) {\n return body as T;\n }\n if (typeof body !== \"object\" || body === null || !(\"data\" in body)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `Response to ${opts.method} ${opts.path} missing 'data' field`,\n undefined,\n undefined,\n res.status,\n );\n }\n return (body as HttpOkEnvelope<T>).data;\n};\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,iBAAgC,OAAO,uBAAuB;;;;;;;;AAa3E,MAAa,oBAAoB,WAAyC;CACxE,MAAM,MAAO,OAAiD;CAC9D,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MACR,iGACF;CAEF,OAAO;AACT;;;;;;;;;;;;;;;;;;ACUA,MAAa,UAAU,OAAU,K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