@gusto/baerly-storage 0.2.0 → 0.3.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +93 -52
- package/dist/API.md +151 -109
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +40 -29
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../packages/client/src/client.ts"],"sourcesContent":["/* eslint-disable no-underscore-dangle -- `_id` and `_meta` are the\n locked wire-shape field names (see `packages/protocol/src/collection-api.ts`\n and `packages/server/src/contract.ts`); we mirror them verbatim\n so the typed client stays structurally compatible. */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n type CollectionNames,\n type DocumentData,\n EMPTY_PREDICATE_WIRE,\n normalizePredicateArg,\n type OrderSpec,\n type PredicateArg,\n type PredicateWire,\n type RowOf,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { CLIENT_CONTEXT } from \"./internal/context.ts\";\nimport { type Fetcher, type RequestContext, request } from \"./request.ts\";\n\n/**\n * Public options for {@link createBaerlyClient}.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport interface BaerlyClientOptions<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Required. The deployed `baerly` server URL — e.g.\n * `https://acme.example.com`. No trailing slash.\n */\n readonly baseUrl: string;\n /**\n * Optional. Defaults to `globalThis.fetch`. Wrap your own to add\n * logging, retries, tracing, or auth-refresh — the entire client\n * routes every request through this one function. This is the\n * `link` middleware story (tRPC) and the `interceptor` story\n * (axios) without new API surface.\n *\n * @example\n * ```ts\n * // Log every request + response.\n * const withLogging: Fetcher = async (req) => {\n * const t0 = performance.now();\n * const res = await globalThis.fetch(req);\n * console.log(`${req.method} ${req.url} → ${res.status} (${Math.round(performance.now() - t0)}ms)`);\n * return res;\n * };\n *\n * // Retry idempotent reads on 5xx (max 3 total attempts, 100ms backoff).\n * const withRetry = (next: Fetcher): Fetcher => async (req) => {\n * for (let i = 0; i < 2; i++) {\n * const res = await next(req.clone());\n * if (res.ok || res.status < 500 || req.method !== \"GET\") return res;\n * await new Promise((r) => setTimeout(r, 100 * (i + 1)));\n * }\n * return next(req);\n * };\n *\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * fetch: withRetry(withLogging),\n * });\n * ```\n *\n * See `dist/API.md` → \"Recipe — wrapping the client `fetch`\"\n * for `onSuccess` / `onError` helpers and a composition pattern.\n */\n readonly fetch?: Fetcher;\n /**\n * Optional. Forwarded on every request. Typically\n * `{ Authorization: \"Bearer <token>\" }`. For credential refresh\n * (fresh JWT per call, 401-driven re-issue, etc.) wrap\n * {@link BaerlyClientOptions.fetch} instead — see the retry +\n * logging examples above.\n */\n readonly headers?: Headers | Record<string, string>;\n /**\n * Optional. **Type-only** — the runtime client does not read this\n * field; it exists so `client.collection(name)` can narrow `name` to\n * declared collection names and infer the row type from\n * `collections[name].schema`. Bind the type via the generic\n * parameter using `import type` so the server-side storage\n * adapter and secrets in `baerly.config.ts` do not enter the\n * browser bundle:\n *\n * ```ts\n * import type config from \"./baerly.config.ts\";\n * const client = createBaerlyClient<typeof config>({ baseUrl });\n * await client.collection(\"tickets\").first(); // Promise<Ticket | undefined>\n * ```\n *\n * Skip the type parameter to fall back to the per-call generic\n * `client.collection(\"tickets\")` form.\n */\n readonly config?: TConfig;\n}\n\n/**\n * Trailing-options bag accepted by every terminal. Today this is\n * only `signal`, so the type is split out for readability rather\n * than forcing every call site to ascribe `{ signal?: AbortSignal }`.\n * When other per-call options land (timeout, idempotency key, etc.)\n * they belong here.\n */\nexport interface TerminalOptions {\n /**\n * Cancels this specific request. React effect cleanup is the\n * canonical caller:\n *\n * ```ts\n * useEffect(() => {\n * const ac = new AbortController();\n * client.collection(\"tickets\").where(p).all({ signal: ac.signal }).then(setRows);\n * return () => ac.abort();\n * }, [predicateKey]);\n * ```\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Client-side mirror of `Collection<T>` from `@baerly/protocol`. Cheap\n * handle; constructs no I/O. Same method names as the in-process\n * `Collection<T>`, but every terminal also accepts a trailing\n * {@link TerminalOptions} bag carrying `{ signal }`.\n *\n * By-id mutation verbs (`update`, `replace`, `delete`) live here;\n * predicate-aware bulk mutation has no HTTP route today and is\n * intentionally absent from {@link ClientQuery}.\n *\n * @template T — document shape. `_id` is always present on rows\n * returned from the server.\n */\nexport interface ClientCollection<T extends DocumentData = DocumentData> {\n readonly name: string;\n /** First document in the whole collection or `undefined`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every document in the whole collection. Pair with `.where(...).limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count every row in the collection (equivalent to `.where({}).count()`). */\n count(opts?: TerminalOptions): Promise<number>;\n /** Fetch one document by primary key. Returns `undefined` when the id is unknown. */\n get(id: string, opts?: TerminalOptions): Promise<T | undefined>;\n /**\n * Filter rows. Two shapes:\n *\n * - **Object literal** — equality only.\n * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)` for the\n * operator vocabulary.\n *\n * Chained calls AND-merge across shapes.\n */\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n /** Order modifier; last call wins. */\n order(spec: OrderSpec<T>): ClientQuery<T>;\n /** Limit modifier; last call wins. */\n limit(n: number): ClientQuery<T>;\n /** Insert a new document. Returns the server-assigned `_id`. */\n insert(doc: Partial<T> & DocumentData, opts?: TerminalOptions): Promise<{ readonly _id: string }>;\n /** JSON-merge-patch applied to one row by primary key. */\n update(\n id: string,\n patch: Partial<T>,\n opts?: TerminalOptions,\n ): Promise<{ readonly modified: number }>;\n /** Whole-document replace on one row by primary key. */\n replace(id: string, doc: T, opts?: TerminalOptions): Promise<void>;\n /** Delete one row by primary key. Returns `{ deleted: 0 }` on 404 (not an error). */\n delete(id: string, opts?: TerminalOptions): Promise<{ readonly deleted: number }>;\n}\n\n/**\n * Client-side mirror of `Query<T>` from `@baerly/protocol`. See\n * {@link ClientCollection} for the method-shape contract.\n *\n * Read-only over HTTP: by-id mutation lives on {@link ClientCollection}\n * directly. Predicate-aware bulk mutation is server-only — the HTTP\n * surface has no route for it.\n */\nexport interface ClientQuery<T extends DocumentData = DocumentData> {\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n order(spec: OrderSpec<T>): ClientQuery<T>;\n limit(n: number): ClientQuery<T>;\n /** First match or `undefined`. Issues `GET /v1/c/:collection?...&limit=1`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every matching document. Pair with `.limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count matching rows. Issues `GET /v1/count?collection=&where=`; server returns a scalar. */\n count(opts?: TerminalOptions): Promise<number>;\n}\n\n/**\n * Returned by {@link createBaerlyClient}. The typed entry point.\n *\n * `BaerlyClient` does NOT expose a `transaction(...)` method:\n * the server has no HTTP route for atomic batch commit today (see\n * `packages/server/src/http/router.ts`). Issuing N HTTP requests\n * from the client would silently break the single-CAS invariant.\n * If you need atomic multi-row mutation today, expose a business-\n * level RPC on the server that calls `db.transaction(...)` in-\n * process.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({ baseUrl: \"https://api.example.com\" });\n * const { _id } = await client.collection(\"tickets\").insert({ title: \"hi\" });\n * const row = await client.collection(\"tickets\").get(_id);\n * ```\n */\nexport interface BaerlyClient<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Typed collection handle. Cheap; constructs no I/O.\n *\n * When `TConfig` is bound (via `options.config`) and `name` is one\n * of the declared collection names, the row type is inferred from\n * `TConfig[\"collections\"][name][\"schema\"]`. Otherwise the row type\n * defaults to `DocumentData` and the call accepts any string name —\n * matching the in-process `Db.collection` shape.\n */\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): ClientCollection<RowOf<TConfig, N> & DocumentData>;\n}\n\n/**\n * Construct a typed HTTP client over the locked `/v1/...` routes.\n * Returns a {@link BaerlyClient} with the same surface as the\n * in-process `Db.collection(...)` API.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport const createBaerlyClient = <TConfig extends BaerlyConfig = UnboundConfig>(\n options: BaerlyClientOptions<TConfig>,\n): BaerlyClient<TConfig> => {\n const ctx: RequestContext = {\n baseUrl: options.baseUrl,\n fetch: options.fetch ?? ((req) => globalThis.fetch(req)),\n headers: new Headers(options.headers ?? {}),\n };\n const client = {\n [CLIENT_CONTEXT]: ctx,\n collection<T extends DocumentData = DocumentData>(name: string): ClientCollection<T> {\n return makeClientCollection<T>(ctx, name);\n },\n };\n return client as BaerlyClient<TConfig>;\n};\n\n/** Query-state carried across the chainable modifiers. */\ninterface QueryState {\n readonly wire: PredicateWire;\n readonly order: OrderSpec<DocumentData> | undefined;\n readonly limit: number | undefined;\n}\n\nconst emptyState: QueryState = {\n wire: EMPTY_PREDICATE_WIRE,\n order: undefined,\n limit: undefined,\n};\n\nconst makeClientCollection = <T extends DocumentData>(\n ctx: RequestContext,\n name: string,\n): ClientCollection<T> => {\n const collectionForQuery = makeClientQuery<T>(ctx, name, emptyState);\n const idPath = (id: string): string =>\n `/v1/c/${encodeURIComponent(name)}/${encodeURIComponent(id)}`;\n return {\n name,\n where: (predicate) => collectionForQuery.where(predicate),\n order: (spec) => collectionForQuery.order(spec),\n limit: (n) => collectionForQuery.limit(n),\n first: (opts) => collectionForQuery.first(opts),\n all: (opts) => collectionForQuery.all(opts),\n count: (opts) => collectionForQuery.count(opts),\n async get(id, opts): Promise<T | undefined> {\n try {\n return await request<T>(ctx, {\n method: \"GET\",\n path: idPath(id),\n signal: opts?.signal,\n });\n } catch (error) {\n // 404 on GET → unknown id. Mirrors `Db.collection().get(id)` which\n // resolves `undefined` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return undefined;\n }\n throw error;\n }\n },\n async insert(doc, opts): Promise<{ readonly _id: string }> {\n return request<{ _id: string }>(ctx, {\n method: \"POST\",\n path: `/v1/c/${encodeURIComponent(name)}`,\n body: { doc },\n signal: opts?.signal,\n });\n },\n async update(id, patch, opts): Promise<{ readonly modified: number }> {\n return request<{ modified: number }>(ctx, {\n method: \"PATCH\",\n path: idPath(id),\n body: { patch },\n signal: opts?.signal,\n });\n },\n async replace(id, doc, opts): Promise<void> {\n // PUT = whole-document overwrite. NOT PATCH — PATCH would be\n // RFC 7386 merge-patch and silently retain omitted fields from\n // the prior doc.\n await request<{ modified: number }>(ctx, {\n method: \"PUT\",\n path: idPath(id),\n body: { doc },\n signal: opts?.signal,\n });\n },\n async delete(id, opts): Promise<{ readonly deleted: number }> {\n try {\n await request<undefined>(ctx, {\n method: \"DELETE\",\n path: idPath(id),\n signal: opts?.signal,\n });\n return { deleted: 1 };\n } catch (error) {\n // 404 on DELETE → \"no row matched\". Mirrors `Query.delete()`\n // which returns `{ deleted: 0 }` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return { deleted: 0 };\n }\n throw error;\n }\n },\n };\n};\n\nconst makeClientQuery = <T extends DocumentData>(\n ctx: RequestContext,\n collectionName: string,\n state: QueryState,\n): ClientQuery<T> => {\n const listParams = (): URLSearchParams => {\n const params = new URLSearchParams();\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n if (state.order !== undefined && Object.keys(state.order).length > 0) {\n params.set(\"order\", JSON.stringify(state.order));\n }\n if (state.limit !== undefined) {\n params.set(\"limit\", String(state.limit));\n }\n return params;\n };\n\n const listPath = (override?: { limit?: number }): string => {\n const params = listParams();\n if (override?.limit !== undefined) {\n params.set(\"limit\", String(override.limit));\n }\n const qs = params.toString();\n return `/v1/c/${encodeURIComponent(collectionName)}${qs.length > 0 ? `?${qs}` : \"\"}`;\n };\n\n return {\n where: (predicate): ClientQuery<T> => {\n // Normalise the incoming arg (object or callback) to a wire and\n // concatenate clauses with any prior wire. The server's\n // `parseWhereParam` runs `validateWire` on arrival, so empty\n // `in` / conflicting `eq` / unsatisfiable interval surface as\n // a 400 `InvalidConfig` / `UnsatisfiablePredicate` from the\n // HTTP layer — no client-side merger needed. Skipping the\n // satisfiability check here keeps the SPA bundle out of the\n // wire-merger / per-field-fold code path.\n const incoming = normalizePredicateArg<T>(predicate);\n const merged: PredicateWire =\n state.wire.clauses.length === 0\n ? incoming\n : { clauses: [...state.wire.clauses, ...incoming.clauses] };\n return makeClientQuery<T>(ctx, collectionName, { ...state, wire: merged });\n },\n order: (spec): ClientQuery<T> =>\n makeClientQuery<T>(ctx, collectionName, {\n ...state,\n order: spec as OrderSpec<DocumentData>,\n }),\n limit: (n): ClientQuery<T> => makeClientQuery<T>(ctx, collectionName, { ...state, limit: n }),\n\n async first(opts): Promise<T | undefined> {\n // Mirrors `Db.first()` which sets `limit: 1` on its underlying\n // list call; override the query-state limit for this terminal\n // only (chained `.limit(n).first()` semantics: `first` wins).\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath({ limit: 1 }),\n signal: opts?.signal,\n });\n return data[0];\n },\n async all(opts): Promise<T[]> {\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath(),\n signal: opts?.signal,\n });\n return [...data];\n },\n async count(opts): Promise<number> {\n const params = new URLSearchParams();\n params.set(\"collection\", collectionName);\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n const { count } = await request<{ count: number }>(ctx, {\n method: \"GET\",\n path: `/v1/count?${params.toString()}`,\n signal: opts?.signal,\n });\n return count;\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoPA,MAAa,sBACX,YAC0B;CAC1B,MAAM,MAAsB;EAC1B,SAAS,QAAQ;EACjB,OAAO,QAAQ,WAAW,QAAQ,WAAW,MAAM,GAAG;EACtD,SAAS,IAAI,QAAQ,QAAQ,WAAW,CAAC,CAAC;CAC5C;CAOA,OAAO;GALJ,iBAAiB;EAClB,WAAkD,MAAmC;GACnF,OAAO,qBAAwB,KAAK,IAAI;EAC1C;CAEU;AACd;AASA,MAAM,aAAyB;CAC7B,MAAM;CACN,OAAO,KAAA;CACP,OAAO,KAAA;AACT;AAEA,MAAM,wBACJ,KACA,SACwB;CACxB,MAAM,qBAAqB,gBAAmB,KAAK,MAAM,UAAU;CACnE,MAAM,UAAU,OACd,SAAS,mBAAmB,IAAI,EAAE,GAAG,mBAAmB,EAAE;CAC5D,OAAO;EACL;EACA,QAAQ,cAAc,mBAAmB,MAAM,SAAS;EACxD,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,QAAQ,MAAM,mBAAmB,MAAM,CAAC;EACxC,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,MAAM,SAAS,mBAAmB,IAAI,IAAI;EAC1C,QAAQ,SAAS,mBAAmB,MAAM,IAAI;EAC9C,MAAM,IAAI,IAAI,MAA8B;GAC1C,IAAI;IACF,OAAO,MAAM,QAAW,KAAK;KAC3B,QAAQ;KACR,MAAM,OA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AQ;IACR,MAAM,aAAa,OAAO,SAAS;IACnC,QAAQ,MAAM;GAChB,CAAC;GACD,OAAO;EACT;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../packages/client/src/client.ts"],"sourcesContent":["/* eslint-disable no-underscore-dangle -- `_id` and `_meta` are the\n locked wire-shape field names (see `packages/protocol/src/collection-api.ts`\n and `packages/server/src/contract.ts`); we mirror them verbatim\n so the typed client stays structurally compatible. */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n type CollectionNames,\n type DocumentData,\n EMPTY_PREDICATE_WIRE,\n normalizePredicateArg,\n type OrderSpec,\n type PredicateArg,\n type PredicateWire,\n type RowOf,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { CLIENT_CONTEXT } from \"./internal/context.ts\";\nimport { type Fetcher, type RequestContext, request } from \"./request.ts\";\n\n/**\n * Public options for {@link createBaerlyClient}.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport interface BaerlyClientOptions<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Required. The deployed `baerly` server URL — e.g.\n * `https://acme.example.com`. No trailing slash.\n */\n readonly baseUrl: string;\n /**\n * Optional. Defaults to `globalThis.fetch`. Wrap your own to add\n * logging, retries, tracing, or auth-refresh — the entire client\n * routes every request through this one function. This is the\n * `link` middleware story (tRPC) and the `interceptor` story\n * (axios) without new API surface.\n *\n * @example\n * ```ts\n * // Log every request + response.\n * const withLogging: Fetcher = async (req) => {\n * const t0 = performance.now();\n * const res = await globalThis.fetch(req);\n * console.log(`${req.method} ${req.url} → ${res.status} (${Math.round(performance.now() - t0)}ms)`);\n * return res;\n * };\n *\n * // Retry idempotent reads on 5xx (max 3 total attempts, 100ms backoff).\n * const withRetry = (next: Fetcher): Fetcher => async (req) => {\n * for (let i = 0; i < 2; i++) {\n * const res = await next(req.clone());\n * if (res.ok || res.status < 500 || req.method !== \"GET\") return res;\n * await new Promise((r) => setTimeout(r, 100 * (i + 1)));\n * }\n * return next(req);\n * };\n *\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * fetch: withRetry(withLogging),\n * });\n * ```\n *\n * See `dist/API.md` → \"Recipe — wrapping the client `fetch`\"\n * for `onSuccess` / `onError` helpers and a composition pattern.\n */\n readonly fetch?: Fetcher;\n /**\n * Optional. Forwarded on every request. Typically\n * `{ Authorization: \"Bearer <token>\" }`. For credential refresh\n * (fresh JWT per call, 401-driven re-issue, etc.) wrap\n * {@link BaerlyClientOptions.fetch} instead — see the retry +\n * logging examples above.\n */\n readonly headers?: Headers | Record<string, string>;\n /**\n * Optional. **Type-only** — the runtime client does not read this\n * field; it exists so `client.collection(name)` can narrow `name` to\n * declared collection names and infer the row type from\n * `collections[name].schema`. Bind the type via the generic\n * parameter using `import type` so the server-side storage\n * adapter and secrets in `baerly.config.ts` do not enter the\n * browser bundle:\n *\n * ```ts\n * import type config from \"./baerly.config.ts\";\n * const client = createBaerlyClient<typeof config>({ baseUrl });\n * await client.collection(\"tickets\").first(); // Promise<Ticket | undefined>\n * ```\n *\n * Skip the type parameter to fall back to the per-call generic\n * `client.collection(\"tickets\")` form.\n */\n readonly config?: TConfig;\n}\n\n/**\n * Trailing-options bag accepted by every terminal. Today this is\n * only `signal`, so the type is split out for readability rather\n * than forcing every call site to ascribe `{ signal?: AbortSignal }`.\n * When other per-call options land (timeout, idempotency key, etc.)\n * they belong here.\n */\nexport interface TerminalOptions {\n /**\n * Cancels this specific request. React effect cleanup is the\n * canonical caller:\n *\n * ```ts\n * useEffect(() => {\n * const ac = new AbortController();\n * client.collection(\"tickets\").where(p).all({ signal: ac.signal }).then(setRows);\n * return () => ac.abort();\n * }, [predicateKey]);\n * ```\n */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Client-side mirror of `Collection<T>` from `@baerly/protocol`. Cheap\n * handle; constructs no I/O. Same method names as the in-process\n * `Collection<T>`, but every terminal also accepts a trailing\n * {@link TerminalOptions} bag carrying `{ signal }`.\n *\n * By-id mutation verbs (`update`, `replace`, `delete`) live here;\n * predicate-aware bulk mutation has no HTTP route today and is\n * intentionally absent from {@link ClientQuery}.\n *\n * @template T — document shape. `_id` is always present on rows\n * returned from the server.\n */\nexport interface ClientCollection<T extends DocumentData = DocumentData> {\n readonly name: string;\n /** First document in the whole collection or `undefined`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every document in the whole collection. Pair with `.where(...).limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count every row in the collection (equivalent to `.where({}).count()`). */\n count(opts?: TerminalOptions): Promise<number>;\n /** Fetch one document by primary key. Returns `undefined` when the id is unknown. */\n get(id: string, opts?: TerminalOptions): Promise<T | undefined>;\n /**\n * Filter rows. Two shapes:\n *\n * - **Object literal** — equality only.\n * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)` for the\n * operator vocabulary.\n *\n * Chained calls AND-merge across shapes.\n */\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n /** Order modifier; last call wins. */\n order(spec: OrderSpec<T>): ClientQuery<T>;\n /** Limit modifier; last call wins. */\n limit(n: number): ClientQuery<T>;\n /** Insert a new document. Returns the server-assigned `_id`. */\n insert(doc: Partial<T> & DocumentData, opts?: TerminalOptions): Promise<{ readonly _id: string }>;\n /** JSON-merge-patch applied to one row by primary key. */\n update(\n id: string,\n patch: Partial<T>,\n opts?: TerminalOptions,\n ): Promise<{ readonly modified: number }>;\n /** Whole-document replace on one row by primary key. */\n replace(id: string, doc: T, opts?: TerminalOptions): Promise<void>;\n /** Delete one row by primary key. Returns `{ deleted: 0 }` on 404 (not an error). */\n delete(id: string, opts?: TerminalOptions): Promise<{ readonly deleted: number }>;\n}\n\n/**\n * Client-side mirror of `Query<T>` from `@baerly/protocol`. See\n * {@link ClientCollection} for the method-shape contract.\n *\n * Read-only over HTTP: by-id mutation lives on {@link ClientCollection}\n * directly. Predicate-aware bulk mutation is server-only — the HTTP\n * surface has no route for it.\n */\nexport interface ClientQuery<T extends DocumentData = DocumentData> {\n where(predicate: PredicateArg<T>): ClientQuery<T>;\n order(spec: OrderSpec<T>): ClientQuery<T>;\n limit(n: number): ClientQuery<T>;\n /** First match or `undefined`. Issues `GET /v1/c/:collection?...&limit=1`. */\n first(opts?: TerminalOptions): Promise<T | undefined>;\n /** Every matching document. Pair with `.limit(n)` on large collections. */\n all(opts?: TerminalOptions): Promise<T[]>;\n /** Count matching rows. Issues `GET /v1/count?collection=&where=`; server returns a scalar. */\n count(opts?: TerminalOptions): Promise<number>;\n}\n\n/**\n * Returned by {@link createBaerlyClient}. The typed entry point.\n *\n * `BaerlyClient` is read + single-write RPC: reads and by-id\n * mutations (`insert` / `update` / `replace` / `delete`), one\n * document per call. There is no multi-document atomic write — the\n * document is the atomic unit, and the server exposes no batch route.\n * If you need to fan a write across several documents server-side,\n * expose a business-level RPC on the server that drives\n * `db.collection(...)` in-process.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({ baseUrl: \"https://api.example.com\" });\n * const { _id } = await client.collection(\"tickets\").insert({ title: \"hi\" });\n * const row = await client.collection(\"tickets\").get(_id);\n * ```\n */\nexport interface BaerlyClient<TConfig extends BaerlyConfig = UnboundConfig> {\n /**\n * Typed collection handle. Cheap; constructs no I/O.\n *\n * When `TConfig` is bound (via `options.config`) and `name` is one\n * of the declared collection names, the row type is inferred from\n * `TConfig[\"collections\"][name][\"schema\"]`. Otherwise the row type\n * defaults to `DocumentData` and the call accepts any string name —\n * matching the in-process `Db.collection` shape.\n */\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): ClientCollection<RowOf<TConfig, N> & DocumentData>;\n}\n\n/**\n * Construct a typed HTTP client over the locked `/v1/...` routes.\n * Returns a {@link BaerlyClient} with the same surface as the\n * in-process `Db.collection(...)` API.\n *\n * @example\n * ```ts\n * const client = createBaerlyClient({\n * baseUrl: \"https://api.example.com\",\n * headers: { Authorization: \"Bearer <token>\" },\n * });\n * ```\n */\nexport const createBaerlyClient = <TConfig extends BaerlyConfig = UnboundConfig>(\n options: BaerlyClientOptions<TConfig>,\n): BaerlyClient<TConfig> => {\n const ctx: RequestContext = {\n baseUrl: options.baseUrl,\n fetch: options.fetch ?? ((req) => globalThis.fetch(req)),\n headers: new Headers(options.headers ?? {}),\n };\n const client = {\n [CLIENT_CONTEXT]: ctx,\n collection<T extends DocumentData = DocumentData>(name: string): ClientCollection<T> {\n return makeClientCollection<T>(ctx, name);\n },\n };\n return client as BaerlyClient<TConfig>;\n};\n\n/** Query-state carried across the chainable modifiers. */\ninterface QueryState {\n readonly wire: PredicateWire;\n readonly order: OrderSpec<DocumentData> | undefined;\n readonly limit: number | undefined;\n}\n\nconst emptyState: QueryState = {\n wire: EMPTY_PREDICATE_WIRE,\n order: undefined,\n limit: undefined,\n};\n\nconst makeClientCollection = <T extends DocumentData>(\n ctx: RequestContext,\n name: string,\n): ClientCollection<T> => {\n const collectionForQuery = makeClientQuery<T>(ctx, name, emptyState);\n const idPath = (id: string): string =>\n `/v1/c/${encodeURIComponent(name)}/${encodeURIComponent(id)}`;\n return {\n name,\n where: (predicate) => collectionForQuery.where(predicate),\n order: (spec) => collectionForQuery.order(spec),\n limit: (n) => collectionForQuery.limit(n),\n first: (opts) => collectionForQuery.first(opts),\n all: (opts) => collectionForQuery.all(opts),\n count: (opts) => collectionForQuery.count(opts),\n async get(id, opts): Promise<T | undefined> {\n try {\n return await request<T>(ctx, {\n method: \"GET\",\n path: idPath(id),\n signal: opts?.signal,\n });\n } catch (error) {\n // 404 on GET → unknown id. Mirrors `Db.collection().get(id)` which\n // resolves `undefined` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return undefined;\n }\n throw error;\n }\n },\n async insert(doc, opts): Promise<{ readonly _id: string }> {\n return request<{ _id: string }>(ctx, {\n method: \"POST\",\n path: `/v1/c/${encodeURIComponent(name)}`,\n body: { doc },\n signal: opts?.signal,\n });\n },\n async update(id, patch, opts): Promise<{ readonly modified: number }> {\n return request<{ modified: number }>(ctx, {\n method: \"PATCH\",\n path: idPath(id),\n body: { patch },\n signal: opts?.signal,\n });\n },\n async replace(id, doc, opts): Promise<void> {\n // PUT = whole-document overwrite. NOT PATCH — PATCH would be\n // RFC 7386 merge-patch and silently retain omitted fields from\n // the prior doc.\n await request<{ modified: number }>(ctx, {\n method: \"PUT\",\n path: idPath(id),\n body: { doc },\n signal: opts?.signal,\n });\n },\n async delete(id, opts): Promise<{ readonly deleted: number }> {\n try {\n await request<undefined>(ctx, {\n method: \"DELETE\",\n path: idPath(id),\n signal: opts?.signal,\n });\n return { deleted: 1 };\n } catch (error) {\n // 404 on DELETE → \"no row matched\". Mirrors `Query.delete()`\n // which returns `{ deleted: 0 }` rather than throwing.\n if (error instanceof BaerlyError && error.code === \"NotFound\") {\n return { deleted: 0 };\n }\n throw error;\n }\n },\n };\n};\n\nconst makeClientQuery = <T extends DocumentData>(\n ctx: RequestContext,\n collectionName: string,\n state: QueryState,\n): ClientQuery<T> => {\n const listParams = (): URLSearchParams => {\n const params = new URLSearchParams();\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n if (state.order !== undefined && Object.keys(state.order).length > 0) {\n params.set(\"order\", JSON.stringify(state.order));\n }\n if (state.limit !== undefined) {\n params.set(\"limit\", String(state.limit));\n }\n return params;\n };\n\n const listPath = (override?: { limit?: number }): string => {\n const params = listParams();\n if (override?.limit !== undefined) {\n params.set(\"limit\", String(override.limit));\n }\n const qs = params.toString();\n return `/v1/c/${encodeURIComponent(collectionName)}${qs.length > 0 ? `?${qs}` : \"\"}`;\n };\n\n return {\n where: (predicate): ClientQuery<T> => {\n // Normalise the incoming arg (object or callback) to a wire and\n // concatenate clauses with any prior wire. The server's\n // `parseWhereParam` runs `validateWire` on arrival, so empty\n // `in` / conflicting `eq` / unsatisfiable interval surface as\n // a 400 `InvalidConfig` / `UnsatisfiablePredicate` from the\n // HTTP layer — no client-side merger needed. Skipping the\n // satisfiability check here keeps the SPA bundle out of the\n // wire-merger / per-field-fold code path.\n const incoming = normalizePredicateArg<T>(predicate);\n const merged: PredicateWire =\n state.wire.clauses.length === 0\n ? incoming\n : { clauses: [...state.wire.clauses, ...incoming.clauses] };\n return makeClientQuery<T>(ctx, collectionName, { ...state, wire: merged });\n },\n order: (spec): ClientQuery<T> =>\n makeClientQuery<T>(ctx, collectionName, {\n ...state,\n order: spec as OrderSpec<DocumentData>,\n }),\n limit: (n): ClientQuery<T> => makeClientQuery<T>(ctx, collectionName, { ...state, limit: n }),\n\n async first(opts): Promise<T | undefined> {\n // Mirrors `Db.first()` which sets `limit: 1` on its underlying\n // list call; override the query-state limit for this terminal\n // only (chained `.limit(n).first()` semantics: `first` wins).\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath({ limit: 1 }),\n signal: opts?.signal,\n });\n return data[0];\n },\n async all(opts): Promise<T[]> {\n const data = await request<ReadonlyArray<T>>(ctx, {\n method: \"GET\",\n path: listPath(),\n signal: opts?.signal,\n });\n return [...data];\n },\n async count(opts): Promise<number> {\n const params = new URLSearchParams();\n params.set(\"collection\", collectionName);\n if (state.wire.clauses.length > 0) {\n params.set(\"where\", JSON.stringify(state.wire));\n }\n const { count } = await request<{ count: number }>(ctx, {\n method: \"GET\",\n path: `/v1/count?${params.toString()}`,\n signal: opts?.signal,\n });\n return count;\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoPA,MAAa,sBACX,YAC0B;CAC1B,MAAM,MAAsB;EAC1B,SAAS,QAAQ;EACjB,OAAO,QAAQ,WAAW,QAAQ,WAAW,MAAM,GAAG;EACtD,SAAS,IAAI,QAAQ,QAAQ,WAAW,CAAC,CAAC;CAC5C;CAOA,OAAO;GALJ,iBAAiB;EAClB,WAAkD,MAAmC;GACnF,OAAO,qBAAwB,KAAK,IAAI;EAC1C;CAEU;AACd;AASA,MAAM,aAAyB;CAC7B,MAAM;CACN,O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O,OAAO;EAAE,CAAC;EAE5F,MAAM,MAAM,MAA8B;GASxC,QAAO,MALY,QAA0B,KAAK;IAChD,QAAQ;IACR,MAAM,SAAS,EAAE,OAAO,EAAE,CAAC;IAC3B,QAAQ,MAAM;GAChB,CAAC,EAAA,CACW;EACd;EACA,MAAM,IAAI,MAAoB;GAM5B,OAAO,CAAC,GAAG,MALQ,QAA0B,KAAK;IAChD,QAAQ;IACR,MAAM,SAAS;IACf,QAAQ,MAAM;GAChB,CAAC,CACc;EACjB;EACA,MAAM,MAAM,MAAuB;GACjC,MAAM,SAAS,IAAI,gBAAgB;GACnC,OAAO,IAAI,cAAc,cAAc;GACvC,IAAI,MAAM,KAAK,QAAQ,SAAS,GAC9B,OAAO,IAAI,SAAS,KAAK,UAAU,MAAM,IAAI,CAAC;GAEhD,MAAM,EAAE,UAAU,MAAM,QAA2B,KAAK;IACtD,QAAQ;IACR,MAAM,aAAa,OAAO,SAAS;IACnC,QAAQ,MAAM;GAChB,CAAC;GACD,OAAO;EACT;CACF;AACF"}
|
|
@@ -1,7 +1,171 @@
|
|
|
1
|
+
import { o as uuid, r as parseBucketUri } from "./config-CGyBopy3.js";
|
|
1
2
|
import { o as BaerlyError } from "./baerly.js";
|
|
2
3
|
import { resolve } from "node:path";
|
|
3
4
|
import { existsSync, readFileSync } from "node:fs";
|
|
4
5
|
import { spawn } from "node:child_process";
|
|
6
|
+
//#region ../protocol/src/storage/probe-cas.ts
|
|
7
|
+
const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
|
|
8
|
+
/**
|
|
9
|
+
* Runtime probe that a live `Storage` backend honours the conditional
|
|
10
|
+
* writes the protocol depends on. The storage conformance suite asserts
|
|
11
|
+
* the same semantics in CI for every shipped adapter, but a deployment
|
|
12
|
+
* may point baerly at an arbitrary S3-compatible store; a backend that
|
|
13
|
+
* silently *ignores* these conditionals causes silent corruption — the
|
|
14
|
+
* log-append commit relies on `If-None-Match:"*"` create-if-absent
|
|
15
|
+
* being exactly-one-winner under concurrency (the winning create IS the
|
|
16
|
+
* commit; two winners produce split-brain commit), and the compactor
|
|
17
|
+
* CAS-advances `current.json` with `If-Match` under the no-lease
|
|
18
|
+
* maintenance fold (a backend that returns 200 instead of rejecting a
|
|
19
|
+
* stale `If-Match` causes lost-update corruption). This is the
|
|
20
|
+
* fail-loud, deploy-time analogue of the conformance CAS block.
|
|
21
|
+
*
|
|
22
|
+
* Writes throwaway sentinels under `keyPrefix` and deletes them on
|
|
23
|
+
* the way out (even on failure). Three checks, mirroring the conformance
|
|
24
|
+
* suite:
|
|
25
|
+
* - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
|
|
26
|
+
* - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
|
|
27
|
+
* key must reject (Conflict).
|
|
28
|
+
* - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent
|
|
29
|
+
* writes on a fresh key wins — the linearizability the writer's log-append
|
|
30
|
+
* commit already relies on (`writer.ts`).
|
|
31
|
+
*
|
|
32
|
+
* A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
|
|
33
|
+
* (the contract `Storage.put` documents); anything else — a resolved
|
|
34
|
+
* promise, or a non-Conflict error — is reported as a failed or
|
|
35
|
+
* inconclusive check rather than thrown.
|
|
36
|
+
*/
|
|
37
|
+
const probeCas = async (storage, opts) => {
|
|
38
|
+
const prefix = opts?.keyPrefix ?? "";
|
|
39
|
+
const key = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
40
|
+
const enc = new TextEncoder();
|
|
41
|
+
const signal = opts?.signal;
|
|
42
|
+
const checks = [];
|
|
43
|
+
try {
|
|
44
|
+
await storage.put(key, enc.encode("v1"), { signal });
|
|
45
|
+
try {
|
|
46
|
+
await storage.put(key, enc.encode("v2"), {
|
|
47
|
+
ifMatch: "\"baerly-cas-probe-stale\"",
|
|
48
|
+
signal
|
|
49
|
+
});
|
|
50
|
+
checks.push({
|
|
51
|
+
name: "ifMatch-stale",
|
|
52
|
+
ok: false,
|
|
53
|
+
detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
|
|
54
|
+
});
|
|
55
|
+
} catch (error) {
|
|
56
|
+
checks.push(isConflict(error) ? {
|
|
57
|
+
name: "ifMatch-stale",
|
|
58
|
+
ok: true,
|
|
59
|
+
detail: "stale If-Match rejected (Conflict), as required."
|
|
60
|
+
} : {
|
|
61
|
+
name: "ifMatch-stale",
|
|
62
|
+
ok: false,
|
|
63
|
+
detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
await storage.put(key, enc.encode("v3"), {
|
|
68
|
+
ifNoneMatch: "*",
|
|
69
|
+
signal
|
|
70
|
+
});
|
|
71
|
+
checks.push({
|
|
72
|
+
name: "ifNoneMatch-exists",
|
|
73
|
+
ok: false,
|
|
74
|
+
detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
|
|
75
|
+
});
|
|
76
|
+
} catch (error) {
|
|
77
|
+
checks.push(isConflict(error) ? {
|
|
78
|
+
name: "ifNoneMatch-exists",
|
|
79
|
+
ok: true,
|
|
80
|
+
detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
|
|
81
|
+
} : {
|
|
82
|
+
name: "ifNoneMatch-exists",
|
|
83
|
+
ok: false,
|
|
84
|
+
detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;
|
|
88
|
+
const RACERS = 16;
|
|
89
|
+
try {
|
|
90
|
+
const outcomes = await Promise.allSettled(Array.from({ length: RACERS }, (_unused, i) => storage.put(raceKey, enc.encode(`r${i}`), {
|
|
91
|
+
ifNoneMatch: "*",
|
|
92
|
+
signal
|
|
93
|
+
})));
|
|
94
|
+
const winners = outcomes.filter((o) => o.status === "fulfilled").length;
|
|
95
|
+
const transient = outcomes.filter((o) => o.status === "rejected" && !isConflict(o.reason)).length;
|
|
96
|
+
if (winners > 1) checks.push({
|
|
97
|
+
name: "ifNoneMatch-concurrent",
|
|
98
|
+
ok: false,
|
|
99
|
+
detail: `${winners} of ${RACERS} concurrent create-if-absent writes won (expected at most 1) — create-if-absent is NOT linearizable; the log-append commit would split-brain.`
|
|
100
|
+
});
|
|
101
|
+
else if (winners === 1) if (transient === 0) checks.push({
|
|
102
|
+
name: "ifNoneMatch-concurrent",
|
|
103
|
+
ok: true,
|
|
104
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (Conflict), as required.`
|
|
105
|
+
});
|
|
106
|
+
else checks.push({
|
|
107
|
+
name: "ifNoneMatch-concurrent",
|
|
108
|
+
ok: false,
|
|
109
|
+
detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-Conflict error — inconclusive; retry for a clean race.`
|
|
110
|
+
});
|
|
111
|
+
else checks.push({
|
|
112
|
+
name: "ifNoneMatch-concurrent",
|
|
113
|
+
ok: false,
|
|
114
|
+
detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`
|
|
115
|
+
});
|
|
116
|
+
} finally {
|
|
117
|
+
try {
|
|
118
|
+
await storage.delete(raceKey, signal === void 0 ? void 0 : { signal });
|
|
119
|
+
} catch {}
|
|
120
|
+
}
|
|
121
|
+
} finally {
|
|
122
|
+
try {
|
|
123
|
+
await storage.delete(key, signal === void 0 ? void 0 : { signal });
|
|
124
|
+
} catch {}
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
ok: checks.every((c) => c.ok),
|
|
128
|
+
checks
|
|
129
|
+
};
|
|
130
|
+
};
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/doctor/cas.ts
|
|
133
|
+
/**
|
|
134
|
+
* `baerly doctor --bucket <uri>` — live backend CAS probe.
|
|
135
|
+
*
|
|
136
|
+
* Unlike the cloudflare deploy-invariant walk (which only inspects
|
|
137
|
+
* config files), this mode connects to a real bucket and verifies it
|
|
138
|
+
* honours the conditional writes the protocol depends on: the
|
|
139
|
+
* log-append commit relies on `If-None-Match:"*"` create-if-absent
|
|
140
|
+
* being exactly-one-winner under concurrency (the winning create IS the
|
|
141
|
+
* commit), and the compactor CAS-advances `current.json` with `If-Match`
|
|
142
|
+
* under the no-lease maintenance fold. A store that silently ignores
|
|
143
|
+
* these conditionals causes silent corruption (split-brain commit, or
|
|
144
|
+
* lost updates on a stale `If-Match`) — this is the fail-loud,
|
|
145
|
+
* deploy-time analogue of the conformance CAS block.
|
|
146
|
+
*
|
|
147
|
+
* Writes throwaway sentinels and deletes them; see
|
|
148
|
+
* {@link probeCas}.
|
|
149
|
+
*/
|
|
150
|
+
const CAS_FIX = "Point baerly at an S3-compatible store that honours conditional writes (If-Match + If-None-Match). AWS S3 and Cloudflare R2 honour them. Some S3-compatible endpoints don't enforce them on writes — notably GCS's interop endpoint, which documents these headers as read-only — and a custom gateway / proxy may strip them; this probe exists to catch exactly that. A conformant backend returns 412 on a stale If-Match.";
|
|
151
|
+
/**
|
|
152
|
+
* Run the live CAS round-trip against `storage` and shape the result
|
|
153
|
+
* as a {@link DoctorReport}. Status is `error` iff any sub-check failed
|
|
154
|
+
* (a non-conformant backend is a hard blocker, not a warning).
|
|
155
|
+
*/
|
|
156
|
+
const doctorCas = async (storage, keyPrefix) => {
|
|
157
|
+
const result = await probeCas(storage, { keyPrefix });
|
|
158
|
+
return {
|
|
159
|
+
findings: result.checks.map((c) => ({
|
|
160
|
+
severity: c.ok ? "ok" : "error",
|
|
161
|
+
check: `cas-${c.name}`,
|
|
162
|
+
message: c.detail,
|
|
163
|
+
...c.ok ? {} : { fix: CAS_FIX }
|
|
164
|
+
})),
|
|
165
|
+
status: result.ok ? "ok" : "error"
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
//#endregion
|
|
5
169
|
//#region src/runner.ts
|
|
6
170
|
/**
|
|
7
171
|
* `ProcessRunner` interface + default `node:child_process.spawn`-backed
|
|
@@ -813,6 +977,10 @@ const parseR2Bindings$1 = (source) => {
|
|
|
813
977
|
* Tests inject a {@link ProcessRunner} mock; production uses the
|
|
814
978
|
* default `node:child_process.spawn`-backed implementation.
|
|
815
979
|
*/
|
|
980
|
+
const defaultCasProbe = async (probeBucketUri) => {
|
|
981
|
+
const { storage, keyPrefix } = await parseBucketUri(probeBucketUri);
|
|
982
|
+
return doctorCas(storage, keyPrefix);
|
|
983
|
+
};
|
|
816
984
|
/** Path to `wrangler.jsonc` at the package root. */
|
|
817
985
|
const wranglerPathFor = (repoRoot) => resolve(repoRoot, "wrangler.jsonc");
|
|
818
986
|
/**
|
|
@@ -893,6 +1061,14 @@ const deployCloudflare = async (config, opts = {}) => {
|
|
|
893
1061
|
const repoRoot = opts.cwd ?? config.repoRoot;
|
|
894
1062
|
const wranglerPath = wranglerPathFor(repoRoot);
|
|
895
1063
|
if (!existsSync(wranglerPath)) throw new BaerlyError("InvalidConfig", `baerly deploy: ${wranglerPath} missing. Expected wrangler.jsonc at the package root.`);
|
|
1064
|
+
if (opts.probeBucketUri !== void 0 && opts.probeBucketUri.length > 0) {
|
|
1065
|
+
const report = await (opts.casProbe ?? defaultCasProbe)(opts.probeBucketUri);
|
|
1066
|
+
if (report.status !== "ok") {
|
|
1067
|
+
const failed = report.findings.filter((f) => f.severity === "error").map((f) => `${f.check}: ${f.message}`).join("; ");
|
|
1068
|
+
throw new BaerlyError("NetworkError", `baerly deploy: CAS preflight against ${opts.probeBucketUri} failed — not deploying. ${failed}`);
|
|
1069
|
+
}
|
|
1070
|
+
process.stderr.write(`baerly deploy: CAS preflight OK for ${opts.probeBucketUri}\n`);
|
|
1071
|
+
}
|
|
896
1072
|
const help = await runner.run("wrangler", ["deploy", "--help"], repoRoot);
|
|
897
1073
|
const hasXProvision = help.code === 0 && help.stdout.includes("--x-provision");
|
|
898
1074
|
await warnOnMissingSecrets(runner, repoRoot, config.requiredSecrets ?? ["SHARED_SECRET"]);
|
|
@@ -906,6 +1082,6 @@ const deployCloudflare = async (config, opts = {}) => {
|
|
|
906
1082
|
return (await runner.run("wrangler", ["deploy"], repoRoot)).code;
|
|
907
1083
|
};
|
|
908
1084
|
//#endregion
|
|
909
|
-
export { defaultRunner as a, parse as i, ensureBindings as n, parseR2Bindings as r, deployCloudflare as t };
|
|
1085
|
+
export { defaultRunner as a, parse as i, ensureBindings as n, doctorCas as o, parseR2Bindings as r, deployCloudflare as t };
|
|
910
1086
|
|
|
911
|
-
//# sourceMappingURL=cloudflare-
|
|
1087
|
+
//# sourceMappingURL=cloudflare-Cn2ibODt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloudflare-Cn2ibODt.js","names":["parse","parser.parse","parseR2Bindings","parseR2BindingsFromSource"],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/cli/src/doctor/cas.ts","../packages/cli/src/runner.ts","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/scanner.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/impl/parser.js","../node_modules/.pnpm/jsonc-parser@3.3.1/node_modules/jsonc-parser/lib/esm/main.js","../packages/cli/src/wrangler-patch.ts","../packages/cli/src/deploy/cloudflare.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\nconst isConflict = (error: unknown): boolean =>\n error instanceof BaerlyError && error.code === \"Conflict\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists` / `ifNoneMatch-concurrent`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* these conditionals causes silent corruption — the\n * log-append commit relies on `If-None-Match:\"*\"` create-if-absent\n * being exactly-one-winner under concurrency (the winning create IS the\n * commit; two winners produce split-brain commit), and the compactor\n * CAS-advances `current.json` with `If-Match` under the no-lease\n * maintenance fold (a backend that returns 200 instead of rejecting a\n * stale `If-Match` causes lost-update corruption). This is the\n * fail-loud, deploy-time analogue of the conformance CAS block.\n *\n * Writes throwaway sentinels under `keyPrefix` and deletes them on\n * the way out (even on failure). Three checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (Conflict).\n * - `ifNoneMatch-concurrent`: at most one of N concurrent create-if-absent\n * writes on a fresh key wins — the linearizability the writer's log-append\n * commit already relies on (`writer.ts`).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"Conflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-Conflict error — is reported as a failed or\n * inconclusive check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // ── Check 1: a stale ifMatch must be rejected. ──────────────────\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: '\"baerly-cas-probe-stale\"', signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (Conflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 2: ifNoneMatch:\"*\" over an existing key must reject. ──\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail: 'If-None-Match:\"*\" over an existing key rejected (Conflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 3: at most one of N concurrent ifNoneMatch:\"*\" creates wins. ──\n // The writer already depends on this today: log entries are PUT with\n // ifNoneMatch:\"*\", and a 412 means a peer won that seq (writer.ts). Two\n // winners ⇒ two writers believe they appended the same log seq.\n // Transient non-Conflict losers (e.g. an S3 409\n // ConditionalRequestConflict, which the adapter maps to a retryable\n // NetworkError) are inconclusive — the writer re-issues the same-seq\n // PUT and resolves to 200/412 — not proof of a broken backend. The\n // deploy-time probe still fails closed so operators retry for a clean race.\n const raceKey = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const RACERS = 16;\n try {\n const outcomes = await Promise.allSettled(\n Array.from({ length: RACERS }, (_unused, i) =>\n // Stryker disable next-line StringLiteral: body content irrelevant; only the conditional header + winner count is tested\n storage.put(raceKey, enc.encode(`r${i}`), { ifNoneMatch: \"*\", signal }),\n ),\n );\n const winners = outcomes.filter((o) => o.status === \"fulfilled\").length;\n const transient = outcomes.filter(\n (o) => o.status === \"rejected\" && !isConflict(o.reason),\n ).length;\n if (winners > 1) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `${winners} of ${RACERS} concurrent create-if-absent writes won (expected at most 1) — create-if-absent is NOT linearizable; the log-append commit would split-brain.`,\n });\n } else if (winners === 1) {\n if (transient === 0) {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: true,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won; the rest rejected (Conflict), as required.`,\n });\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `exactly one of ${RACERS} concurrent create-if-absent writes won, but ${transient} loser(s) returned a transient non-Conflict error — inconclusive; retry for a clean race.`,\n });\n }\n } else {\n checks.push({\n name: \"ifNoneMatch-concurrent\",\n ok: false,\n detail: `no create-if-absent write succeeded across ${RACERS} attempts — inconclusive (transient failure or outage), not a linearizability verdict; retry.`,\n });\n }\n } finally {\n try {\n await storage.delete(raceKey, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","/**\n * `baerly doctor --bucket <uri>` — live backend CAS probe.\n *\n * Unlike the cloudflare deploy-invariant walk (which only inspects\n * config files), this mode connects to a real bucket and verifies it\n * honours the conditional writes the protocol depends on: the\n * log-append commit relies on `If-None-Match:\"*\"` create-if-absent\n * being exactly-one-winner under concurrency (the winning create IS the\n * commit), and the compactor CAS-advances `current.json` with `If-Match`\n * under the no-lease maintenance fold. A store that silently ignores\n * these conditionals causes silent corruption (split-brain commit, or\n * lost updates on a stale `If-Match`) — this is the fail-loud,\n * deploy-time analogue of the conformance CAS block.\n *\n * Writes throwaway sentinels and deletes them; see\n * {@link probeCas}.\n */\n\nimport { probeCas, type Storage } from \"@baerly/protocol\";\nimport type { DoctorFinding, DoctorReport } from \"./cloudflare.ts\";\n\nconst CAS_FIX =\n \"Point baerly at an S3-compatible store that honours conditional writes \" +\n \"(If-Match + If-None-Match). AWS S3 and Cloudflare R2 honour them. Some \" +\n \"S3-compatible endpoints don't enforce them on writes — notably GCS's \" +\n \"interop endpoint, which documents these headers as read-only — and a \" +\n \"custom gateway / proxy may strip them; this probe exists to catch \" +\n \"exactly that. A conformant backend returns 412 on a stale If-Match.\";\n\n/**\n * Run the live CAS round-trip against `storage` and shape the result\n * as a {@link DoctorReport}. Status is `error` iff any sub-check failed\n * (a non-conformant backend is a hard blocker, not a warning).\n */\nexport const doctorCas = async (storage: Storage, keyPrefix: string): Promise<DoctorReport> => {\n const result = await probeCas(storage, { keyPrefix });\n const findings: DoctorFinding[] = result.checks.map((c) => ({\n severity: c.ok ? \"ok\" : \"error\",\n check: `cas-${c.name}`,\n message: c.detail,\n ...(c.ok ? {} : { fix: CAS_FIX }),\n }));\n return { findings, status: result.ok ? \"ok\" : \"error\" };\n};\n","/**\n * `ProcessRunner` interface + default `node:child_process.spawn`-backed\n * implementation. Shared by `baerly deploy` and `baerly doctor`, both of\n * which shell out to Wrangler.\n *\n * Tests inject a mock; production uses {@link defaultRunner}. Pass\n * `{ tee: true }` to also write the child's stdout/stderr to the parent\n * process — `baerly deploy` does this so the operator sees Wrangler's\n * progress in real time; `baerly doctor` captures silently for parsing.\n */\n\nimport { spawn } from \"node:child_process\";\n\nexport interface ProcessRunner {\n /**\n * Run `cmd` with `args` in `cwd`. Returns the integer exit code plus\n * captured stdout/stderr. Captured output is also tee'd to the host\n * process's stdout/stderr when the runner was constructed with\n * `{ tee: true }`.\n */\n run(\n cmd: string,\n args: readonly string[],\n cwd: string,\n ): Promise<{ readonly code: number; readonly stdout: string; readonly stderr: string }>;\n}\n\n/**\n * Default `node:child_process.spawn`-backed runner. Inherits stdin and\n * captures stdout/stderr. With `tee: true` the captured bytes are also\n * forwarded to the parent process so the user sees the child's progress\n * in real time.\n */\nexport const defaultRunner = (opts: { readonly tee?: boolean } = {}): ProcessRunner => {\n const tee = opts.tee === true;\n return {\n run: (cmd, args, cwd) =>\n new Promise((res, rej) => {\n const child = spawn(cmd, args as string[], {\n cwd,\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.on(\"data\", (b: Buffer) => {\n stdout += b.toString(\"utf8\");\n if (tee) {\n process.stdout.write(b);\n }\n });\n child.stderr?.on(\"data\", (b: Buffer) => {\n stderr += b.toString(\"utf8\");\n if (tee) {\n process.stderr.write(b);\n }\n });\n child.on(\"error\", rej);\n child.on(\"close\", (code) => res({ code: code ?? 1, stdout, stderr }));\n }),\n };\n};\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","/**\n * Surgical wrangler.jsonc helpers used by `baerly deploy` and the\n * `@gusto/create-baerly-storage` bolt-on flow. All functions are pure (no I/O) —\n * callers do the file read/write. Built on `jsonc-parser` so\n * comments and trailing commas survive round-trips.\n */\n\nimport { parse, modify, applyEdits, type ParseError, type FormattingOptions } from \"jsonc-parser\";\nimport { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * Declared R2 binding extracted from a `wrangler.jsonc` source.\n * Subset of the wrangler schema — we only consume `binding` and\n * `bucket_name`, not the optional preview/jurisdiction fields.\n */\nexport interface R2BindingDeclaration {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Parse declared `r2_buckets[]` from a `wrangler.jsonc` source\n * string. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` shape.\n */\nexport const parseR2Bindings = (source: string): readonly R2BindingDeclaration[] => {\n const errors: ParseError[] = [];\n const obj = parse(source, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { r2_buckets?: unknown }\n | undefined;\n if (errors.length > 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc parse error at offset ${errors[0]!.offset}: ${errors[0]!.error}`,\n );\n }\n if (obj === undefined || typeof obj !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc did not parse to an object`);\n }\n const buckets = obj.r2_buckets;\n if (buckets === undefined) {\n return [];\n }\n if (!Array.isArray(buckets)) {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets must be an array`);\n }\n const out: R2BindingDeclaration[] = [];\n for (const b of buckets) {\n if (b === null || typeof b !== \"object\") {\n throw new BaerlyError(\"InvalidConfig\", `wrangler.jsonc: r2_buckets entry must be an object`);\n }\n const entry = b as { binding?: unknown; bucket_name?: unknown };\n if (typeof entry.binding !== \"string\" || entry.binding.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].binding must be a non-empty string`,\n );\n }\n if (typeof entry.bucket_name !== \"string\" || entry.bucket_name.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `wrangler.jsonc: r2_buckets[].bucket_name must be a non-empty string`,\n );\n }\n out.push({ binding: entry.binding, bucket_name: entry.bucket_name });\n }\n return out;\n};\n\n/**\n * Input spec for a single R2 binding to add or verify in\n * `wrangler.jsonc`. Mirrors `R2BindingDeclaration` in shape but\n * represents caller intent rather than a parsed declaration.\n */\nexport interface R2BindingSpec {\n readonly binding: string;\n readonly bucket_name: string;\n}\n\n/**\n * Flat string→string map of `vars` entries to merge into\n * `wrangler.jsonc`. Existing keys are never overwritten (user wins).\n */\nexport interface VarsSpec {\n readonly [key: string]: string;\n}\n\n/**\n * Result returned by `patchWranglerJsonc`. `text` is the updated\n * JSONC source; `changes` is a human-readable summary of what was\n * added (empty when the file was already up to date).\n */\nexport interface PatchResult {\n readonly text: string;\n readonly changes: readonly string[];\n}\n\n/**\n * Read the `name` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerName = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { name?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.name !== \"string\") {\n return undefined;\n }\n return parsed.name;\n};\n\n/**\n * Read the `main` field from a `wrangler.jsonc` source string.\n * Returns `undefined` on malformed JSONC or when the field is absent.\n * Never throws — designed for caller-friendly inspection.\n */\nexport const readWranglerMain = (source: string): string | undefined => {\n const errors: ParseError[] = [];\n const parsed = parse(source, errors, { allowTrailingComma: true }) as\n | { main?: unknown }\n | undefined;\n if (errors.length > 0 || typeof parsed?.main !== \"string\") {\n return undefined;\n }\n return parsed.main;\n};\n\n// Sniff the indent style of a JSONC source by scanning for the first\n// indented line and inspecting its leading whitespace. The stock\n// `pnpm create cloudflare` template uses tabs; older / hand-rolled\n// `wrangler.jsonc` files commonly use 2- or 4-space indents. Falls\n// back to 2-space when the file has no indented content (e.g. `{}`).\nconst detectIndent = (source: string): FormattingOptions => {\n for (const line of source.split(\"\\n\")) {\n if (line.length === 0 || line.startsWith(\"{\") || line.startsWith(\"}\")) {\n continue;\n }\n const first = line.charAt(0);\n if (first === \"\\t\") {\n return { insertSpaces: false, tabSize: 2, eol: \"\\n\" };\n }\n if (first === \" \") {\n let count = 0;\n while (count < line.length && line.charAt(count) === \" \") {\n count += 1;\n }\n return { insertSpaces: true, tabSize: count, eol: \"\\n\" };\n }\n }\n return { insertSpaces: true, tabSize: 2, eol: \"\\n\" };\n};\n\n/**\n * Idempotently patch a `wrangler.jsonc` source string:\n *\n * - Appends an R2 binding to `r2_buckets[]` unless an entry with\n * the same `binding` name already exists (user wins).\n * - Merges `vars` keys, skipping any key already present (user wins).\n *\n * Comments and trailing commas are preserved by `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — malformed JSONC or\n * invalid `r2_buckets` / `vars` shape.\n */\nexport const patchWranglerJsonc = (\n source: string,\n binding: R2BindingSpec,\n vars: VarsSpec,\n): PatchResult => {\n const existingBindings = parseR2Bindings(source);\n\n const errors: ParseError[] = [];\n const entry = parse(source, errors, { allowTrailingComma: true }) as\n | { vars?: unknown }\n | undefined;\n\n const rawVars = entry?.vars;\n if (rawVars !== undefined) {\n if (typeof rawVars !== \"object\" || rawVars === null || Array.isArray(rawVars)) {\n throw new BaerlyError(\"InvalidConfig\", \"wrangler.jsonc: vars must be an object\");\n }\n }\n const existingVars = (rawVars ?? {}) as Record<string, unknown>;\n\n const formattingOptions = detectIndent(source);\n const changes: string[] = [];\n let text = source;\n\n const bindingAlreadyDeclared = existingBindings.some((b) => b.binding === binding.binding);\n if (!bindingAlreadyDeclared) {\n const edits = modify(text, [\"r2_buckets\", -1], binding, { formattingOptions });\n text = applyEdits(text, edits);\n changes.push(`added r2 binding ${binding.binding} → ${binding.bucket_name}`);\n }\n\n const addedVarKeys: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (!(key in existingVars)) {\n const edits = modify(text, [\"vars\", key], value, { formattingOptions });\n text = applyEdits(text, edits);\n addedVarKeys.push(key);\n }\n }\n if (addedVarKeys.length > 0) {\n changes.push(`merged vars: ${addedVarKeys.join(\", \")}`);\n }\n\n return { text, changes };\n};\n","/**\n * `baerly deploy --target=cloudflare` — one-command Cloudflare\n * Workers deploy.\n *\n * Behavior:\n * 1. Locate `wrangler.jsonc` at the package root.\n * 2. Sniff `wrangler deploy --help` for the `--x-provision` flag.\n * 3. When present, invoke\n * `wrangler deploy --x-provision --x-auto-create` and rely on\n * Wrangler to auto-create the declared R2 buckets.\n * 4. When absent, parse `wrangler.jsonc` for declared\n * `r2_buckets[]`, ensure each bucket exists (creating with\n * `wrangler r2 bucket create` when missing), then run\n * `wrangler deploy` without the experimental flag.\n * 5. Warn (non-fatal) on any `requiredSecret` not present in the\n * Wrangler-reported secret list.\n *\n * No `wrangler secret put` is invoked — that requires interactive\n * stdin and Wrangler is the authority on the user's secret store.\n * Missing secrets surface as actionable hints printed to stderr.\n *\n * Tests inject a {@link ProcessRunner} mock; production uses the\n * default `node:child_process.spawn`-backed implementation.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport type { AppConfig } from \"../config.ts\";\nimport { doctorCas } from \"../doctor/cas.ts\";\nimport type { DoctorReport } from \"../doctor/cloudflare.ts\";\nimport { defaultRunner, type ProcessRunner } from \"../runner.ts\";\nimport {\n parseR2Bindings as parseR2BindingsFromSource,\n type R2BindingDeclaration,\n} from \"../wrangler-patch.ts\";\n\nexport type { ProcessRunner };\n\nexport type { R2BindingDeclaration };\n\n/**\n * Live CAS preflight: resolve a probe bucket URI to a `Storage` and run\n * the {@link doctorCas} round-trip (the same exactly-one-winner /\n * If-Match probe `baerly doctor --bucket` runs). Injectable so tests can\n * force a pass/fail without a live bucket.\n */\nexport type CasProbe = (probeBucketUri: string) => Promise<DoctorReport>;\n\nconst defaultCasProbe: CasProbe = async (probeBucketUri) => {\n const { storage, keyPrefix } = await parseBucketUri(probeBucketUri);\n return doctorCas(storage, keyPrefix);\n};\n\n/** Path to `wrangler.jsonc` at the package root. */\nconst wranglerPathFor = (repoRoot: string): string => resolve(repoRoot, \"wrangler.jsonc\");\n\n/**\n * Parse the declared `r2_buckets[]` array from a `wrangler.jsonc`\n * file. Tolerates comments + trailing commas via `jsonc-parser`.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, parse\n * error, or any entry missing `binding` / `bucket_name`.\n */\nexport const parseR2Bindings = (wranglerPath: string): readonly R2BindingDeclaration[] => {\n if (!existsSync(wranglerPath)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: ${wranglerPath} missing. Expected wrangler.jsonc at the package root.`,\n );\n }\n return parseR2BindingsFromSource(readFileSync(wranglerPath, \"utf8\"));\n};\n\n/**\n * Walk the declared R2 bindings; for each, run `wrangler r2 bucket\n * info <name>` and, on non-zero exit, `wrangler r2 bucket create\n * <name>`. Used as the fallback when `wrangler --x-provision` is\n * unavailable, and directly invoked by `baerly doctor\n * --target=cloudflare --fix`.\n *\n * @throws BaerlyError code=\"NetworkError\" — bucket creation\n * reported a non-zero exit (Wrangler's own error already on\n * stderr).\n */\nexport const ensureBindings = async (\n runner: ProcessRunner,\n cwd: string,\n wranglerPath: string,\n): Promise<void> => {\n const declared = parseR2Bindings(wranglerPath);\n for (const { bucket_name } of declared) {\n const info = await runner.run(\"wrangler\", [\"r2\", \"bucket\", \"info\", bucket_name], cwd);\n if (info.code === 0) {\n continue;\n }\n process.stderr.write(`baerly deploy: creating R2 bucket ${bucket_name}\\n`);\n const created = await runner.run(\"wrangler\", [\"r2\", \"bucket\", \"create\", bucket_name], cwd);\n if (created.code !== 0) {\n throw new BaerlyError(\n \"NetworkError\",\n `baerly deploy: failed to create R2 bucket ${bucket_name} (exit ${created.code})`,\n );\n }\n }\n};\n\n/**\n * Best-effort secret check. `wrangler secret list` emits a JSON\n * array of `{ name, type }` when stdout is piped (Wrangler 4.x\n * default). We parse, diff against `required`, and print\n * actionable hints for each missing secret. Non-fatal — a missing\n * secret blocks the Verifier at runtime, not at deploy time.\n */\nconst warnOnMissingSecrets = async (\n runner: ProcessRunner,\n cwd: string,\n required: readonly string[],\n): Promise<void> => {\n const r = await runner.run(\"wrangler\", [\"secret\", \"list\"], cwd);\n if (r.code !== 0) {\n process.stderr.write(\"baerly deploy: could not list secrets; skipping check\\n\");\n return;\n }\n let configured: readonly string[];\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (!Array.isArray(parsed)) {\n return;\n }\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n } catch {\n return;\n }\n for (const name of required) {\n if (!configured.includes(name)) {\n process.stderr.write(\n `baerly deploy: secret ${name} is required but unset. ` +\n `Run: wrangler secret put ${name}\\n`,\n );\n }\n }\n};\n\n/**\n * Deploy a baerly app to Cloudflare Workers. Returns the integer\n * exit code from the underlying `wrangler deploy` invocation.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `wrangler.jsonc`\n * missing or unparseable.\n * @throws BaerlyError code=\"NetworkError\" — the fallback path\n * could not create a declared R2 bucket.\n */\nexport const deployCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly cwd?: string;\n /** When set, run a live CAS preflight against this bucket URI and abort if it fails. */\n readonly probeBucketUri?: string;\n /** Test seam — overrides the live CAS probe. */\n readonly casProbe?: CasProbe;\n } = {},\n): Promise<number> => {\n const runner = opts.runner ?? defaultRunner({ tee: true });\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = wranglerPathFor(repoRoot);\n if (!existsSync(wranglerPath)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: ${wranglerPath} missing. Expected wrangler.jsonc at the package root.`,\n );\n }\n\n // CAS live-probe preflight (opt-in via --probe-bucket). The winning\n // log create IS the commit, so a backend that doesn't honour\n // create-if-absent / If-Match would silently corrupt — abort BEFORE\n // any wrangler invocation. Throws NetworkError (exit 2) on failure,\n // matching `baerly doctor --bucket`'s exit-2 contract.\n if (opts.probeBucketUri !== undefined && opts.probeBucketUri.length > 0) {\n const report = await (opts.casProbe ?? defaultCasProbe)(opts.probeBucketUri);\n if (report.status !== \"ok\") {\n const failed = report.findings\n .filter((f) => f.severity === \"error\")\n .map((f) => `${f.check}: ${f.message}`)\n .join(\"; \");\n throw new BaerlyError(\n \"NetworkError\",\n `baerly deploy: CAS preflight against ${opts.probeBucketUri} failed — not deploying. ${failed}`,\n );\n }\n process.stderr.write(`baerly deploy: CAS preflight OK for ${opts.probeBucketUri}\\n`);\n }\n\n // Sniff Wrangler for --x-provision support.\n const help = await runner.run(\"wrangler\", [\"deploy\", \"--help\"], repoRoot);\n const hasXProvision = help.code === 0 && help.stdout.includes(\"--x-provision\");\n\n await warnOnMissingSecrets(runner, repoRoot, config.requiredSecrets ?? [\"SHARED_SECRET\"]);\n\n if (hasXProvision) {\n const r = await runner.run(\n \"wrangler\",\n [\"deploy\", \"--x-provision\", \"--x-auto-create\"],\n repoRoot,\n );\n return r.code;\n }\n\n // Fallback: provision via the doctor path then deploy.\n process.stderr.write(\n \"baerly deploy: wrangler --x-provision unavailable; falling back to manual provisioning\\n\",\n );\n await ensureBindings(runner, repoRoot, wranglerPath);\n const r = await runner.run(\"wrangler\", [\"deploy\"], repoRoot);\n return r.code;\n};\n"],"x_google_ignoreList":[3,4,5,6],"mappings":";;;;;;AAIA,MAAM,cAAc,UAClB,iBA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e,gBAAgB,QAAQ;CAC7C,IAAI,CAAC,WAAW,YAAY,GAC1B,MAAM,IAAI,YACR,iBACA,kBAAkB,aAAa,uDACjC;CAQF,IAAI,KAAK,mBAAmB,KAAA,KAAa,KAAK,eAAe,SAAS,GAAG;EACvE,MAAM,SAAS,OAAO,KAAK,YAAY,gBAAA,CAAiB,KAAK,cAAc;EAC3E,IAAI,OAAO,WAAW,MAAM;GAC1B,MAAM,SAAS,OAAO,SACnB,QAAQ,MAAM,EAAE,aAAa,OAAO,CAAC,CACrC,KAAK,MAAM,GAAG,EAAE,MAAM,IAAI,EAAE,SAAS,CAAC,CACtC,KAAK,IAAI;GACZ,MAAM,IAAI,YACR,gBACA,wCAAwC,KAAK,eAAe,2BAA2B,QACzF;EACF;EACA,QAAQ,OAAO,MAAM,uCAAuC,KAAK,eAAe,GAAG;CACrF;CAGA,MAAM,OAAO,MAAM,OAAO,IAAI,YAAY,CAAC,UAAU,QAAQ,GAAG,QAAQ;CACxE,MAAM,gBAAgB,KAAK,SAAS,KAAK,KAAK,OAAO,SAAS,eAAe;CAE7E,MAAM,qBAAqB,QAAQ,UAAU,OAAO,mBAAmB,CAAC,eAAe,CAAC;CAExF,IAAI,eAMF,QAAO,MALS,OAAO,IACrB,YACA;EAAC;EAAU;EAAiB;CAAiB,GAC7C,QACF,EAAA,CACS;CAIX,QAAQ,OAAO,MACb,0FACF;CACA,MAAM,eAAe,QAAQ,UAAU,YAAY;CAEnD,QAAO,MADS,OAAO,IAAI,YAAY,CAAC,QAAQ,GAAG,QAAQ,EAAA,CAClD;AACX"}
|
package/dist/cloudflare.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as BaerlyAppConfig } from "./app-config-
|
|
2
|
-
import { h as Storage, r as Verifier } from "./index-
|
|
3
|
-
import { i as DevLandingOptions } from "./index-
|
|
4
|
-
import { d as ObservabilityConfig } from "./index-
|
|
1
|
+
import { n as BaerlyAppConfig } from "./app-config-BIzyAKzy.js";
|
|
2
|
+
import { h as Storage, r as Verifier } from "./index-DW7GT6M2.js";
|
|
3
|
+
import { i as DevLandingOptions } from "./index-DnBGSeuU.js";
|
|
4
|
+
import { d as ObservabilityConfig } from "./index-Cmsxx-ZN.js";
|
|
5
5
|
|
|
6
6
|
//#region packages/adapter-cloudflare/src/r2-binding-storage.d.ts
|
|
7
7
|
/**
|