# Shared account client
`normalizeAccountId` collapses runs of whitespace and now trims the edges by default. Callers can pass `{ trimEdges: false }` to preserve one space at either edge.
Run `npm test` to check the exported function. The two consumer projects declare a `file:../shared-client` dependency so adjacent local clones can test an unmerged version. Merging or publishing this repository doesn't automatically upgrade another project.
/** Collapse whitespace in a string-like input; returns text without I/O. */
function collapseWhitespace(value) {
return String(value).replace(/\s+/g, " ");
}
/**
* Normalize an account ID, optionally trimming its edges.
* Returns a string; conversion errors propagate. Pure and deterministic.
*/
function normalizeAccountId(value, options = {}) {
const normalized = collapseWhitespace(value);
const trimEdges = options.trimEdges ?? true;
return trimEdges ? normalized.trim() : normalized;
}
module.exports = { normalizeAccountId };
const test = require("node:test");
const assert = require("node:assert/strict");
const { normalizeAccountId } = require("../src/index.js");
test("trims edge whitespace by default", () => {
assert.equal(normalizeAccountId(" ACCT 42 "), "ACCT 42");
});
test("honors an explicit trimEdges option", () => {
assert.equal(normalizeAccountId(" ACCT 42 ", { trimEdges: true }), "ACCT 42");
assert.equal(normalizeAccountId(" ACCT 42 ", { trimEdges: false }), " ACCT 42 ");
});
/** Collapse whitespace in a string-like input; returns text without I/O. */
function compactWhitespace(value) {
return String(value).replace(/\s+/g, " ");
}
/**
* Normalize an account ID, optionally trimming its edges.
* Returns a string; conversion errors propagate. Pure and deterministic.
*/
function normalizeAccountId(value, options = {}) {
const normalized = compactWhitespace(value);
const trimEdges = options.trimEdges ?? false;
return trimEdges ? normalized.trim() : normalized;
}
module.exports = { normalizeAccountId };
{
"name": "billing-worker",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "node --test"
},
"dependencies": {
"@cookbook/shared-client": "file:../shared-client"
}
}
# Billing worker
`accountLookupKey` uses the shared package's default normalization and lowercases the result. The tests check the returned string; there isn't a database or cache in this example.
Clone `shared-client` next to this project, then run `npm install --ignore-scripts --no-audit --no-fund` and `npm test`. The `file:../shared-client` dependency makes the library revision in that clone the version under test.
const { normalizeAccountId } = require("@cookbook/shared-client");
/**
* Return a lowercase lookup key from a message's account ID.
* No datastore is queried or changed; missing messages throw TypeError.
*/
function accountLookupKey(message) {
return normalizeAccountId(message.accountId).toLowerCase();
}
module.exports = { accountLookupKey };
const test = require("node:test");
const assert = require("node:assert/strict");
const { accountLookupKey } = require("../src/worker.js");
test("preserves the existing padded lookup key", () => {
assert.equal(accountLookupKey({ accountId: " ACCT 42 " }), " acct 42 ");
});
test("keeps a key without edge spaces", () => {
assert.equal(accountLookupKey({ accountId: "ACCT 42" }), "acct 42");
});
{
"name": "checkout-service",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "node --test"
},
"dependencies": {
"@cookbook/shared-client": "file:../shared-client"
}
}
# Checkout service
`checkoutRequest` uses the shared package's default normalization when preparing an account identifier. Its tests exercise the actual imported function.
Clone `shared-client` next to this project, then run `npm install --ignore-scripts --no-audit --no-fund` and `npm test`. The manifest points to that adjacent clone, so changing its checked-out library version changes what the tests exercise. These files don't deploy a service or connect to a datastore.
const { normalizeAccountId } = require("@cookbook/shared-client");
/**
* Build a checkout request from an account ID and items.
* Returns a new object without I/O; missing payloads throw TypeError.
*/
function checkoutRequest(payload) {
return {
accountId: normalizeAccountId(payload.accountId),
items: payload.items,
};
}
module.exports = { checkoutRequest };
const test = require("node:test");
const assert = require("node:assert/strict");
const { checkoutRequest } = require("../src/checkout.js");
test("preserves the existing padded account identifier", () => {
assert.equal(checkoutRequest({ accountId: " ACCT 42 ", items: [] }).accountId, " ACCT 42 ");
});
test("keeps an identifier without edge spaces", () => {
assert.equal(checkoutRequest({ accountId: "ACCT 42", items: [] }).accountId, "ACCT 42");
});
# Integration notes
The platform team is considering `@cookbook/shared-client` and its `normalizeAccountId()` helper for a future integration. This project contains only documentation. It doesn't import or execute the package.
{
"name": "@cookbook/shared-client",
"version": "1.0.0",
"private": true,
"main": "src/index.js",
"scripts": {
"test": "node --test"
}
}
# Shared account client
`normalizeAccountId` collapses runs of whitespace. By default it preserves one space at either edge; callers can pass `{ trimEdges: true }` to remove those spaces.
Run `npm test` to check the exported function. The two consumer projects declare a `file:../shared-client` dependency so adjacent local clones can test an unmerged version. Merging or publishing this repository doesn't automatically upgrade another project.
/** Collapse whitespace in a string-like input; returns text without I/O. */
function collapseWhitespace(value) {
return String(value).replace(/\s+/g, " ");
}
/**
* Normalize an account ID, optionally trimming its edges.
* Returns a string; conversion errors propagate. Pure and deterministic.
*/
function normalizeAccountId(value, options = {}) {
const normalized = collapseWhitespace(value);
const trimEdges = options.trimEdges ?? false;
return trimEdges ? normalized.trim() : normalized;
}
module.exports = { normalizeAccountId };
const test = require("node:test");
const assert = require("node:assert/strict");
const { normalizeAccountId } = require("../src/index.js");
test("preserves edge whitespace by default", () => {
assert.equal(normalizeAccountId(" ACCT 42 "), " ACCT 42 ");
});
test("honors an explicit trimEdges option", () => {
assert.equal(normalizeAccountId(" ACCT 42 ", { trimEdges: true }), "ACCT 42");
assert.equal(normalizeAccountId(" ACCT 42 ", { trimEdges: false }), " ACCT 42 ");
});
#!/usr/bin/env python3
"""Run real library and consumer tests against an owned example revision.
Copies fixtures into a temporary directory and installs only the adjacent local
npm package. No GitLab requests, global npm installs, or edits to user clones.
The changed-default case succeeds only when the library passes and each caller
has precisely the expected assertion failure plus its passing no-edge-space test.
"""
import argparse
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
def run_case(case):
"""Return whether the tests match the named example's expected behavior.
Accepts baseline, changed-default, or private-helper. Writes only inside an
automatically cleaned temporary directory, launches npm/node synchronously,
and prints test summaries. Missing tools or install failures raise rather
than masquerading as expected regression failures. Calls are independent.
"""
with tempfile.TemporaryDirectory(prefix="orbit-library-check-") as temporary:
root = Path(temporary)
shutil.copytree(FIXTURES / "projects", root, dirs_exist_ok=True)
if case != "baseline":
shutil.copytree(FIXTURES / "changes" / case, root / "shared-client", dirs_exist_ok=True)
matches = []
for project in ("shared-client", "checkout-service", "billing-worker"):
directory = root / project
if project != "shared-client":
subprocess.run(["npm", "install", "--offline", "--ignore-scripts", "--no-audit",
"--no-fund", "--package-lock=false"], cwd=directory, check=True,
capture_output=True, text=True)
result = subprocess.run(["node", "--test", "--test-reporter=tap"], cwd=directory,
text=True, capture_output=True, check=False)
expect_change = case == "changed-default" and project != "shared-client"
if expect_change:
expected_test = ("preserves the existing padded account identifier"
if project == "checkout-service" else "preserves the existing padded lookup key")
failed_tests = re.findall(r"^not ok \d+ - (.+)$", result.stdout, re.MULTILINE)
ok = (result.returncode == 1 and "ERR_ASSERTION" in result.stdout
and re.search(r"^# pass 1$", result.stdout, re.MULTILINE) is not None
and re.search(r"^# fail 1$", result.stdout, re.MULTILINE) is not None
and failed_tests == [expected_test])
label = "CHANGE OBSERVED (1 expected assertion failure, 1 passing test)"
else:
ok = (result.returncode == 0
and re.search(r"^# pass 2$", result.stdout, re.MULTILINE) is not None
and re.search(r"^# fail 0$", result.stdout, re.MULTILINE) is not None)
label = "PASS (2 tests)"
matches.append(ok)
print(f"{case}: {project}: {label if ok else 'UNEXPECTED RESULT'}")
if not ok:
print(result.stdout + result.stderr)
return all(matches)
def main():
"""Read one case flag, run local checks, and return zero only on a match.
No external configuration is loaded. Argparse reports unknown case names;
subprocess and filesystem failures propagate with a nonzero exit status.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--case", choices=("baseline", "changed-default", "private-helper"), required=True)
args = parser.parse_args()
return 0 if run_case(args.case) else 1
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
"""Create an isolated, private four-project example through authenticated glab.
Without --apply this prints a preview and performs no network or filesystem
writes. Applying creates a new subgroup, source commits, and two unmerged MRs.
Existing groups aren't reused. Partial failures leave resources for inspection;
nothing is deleted, and credentials stay with glab rather than in these files.
"""
import argparse
import json
from pathlib import Path
import re
import subprocess
import sys
from urllib.parse import quote
FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
PROJECTS = ("shared-client", "checkout-service", "billing-worker", "integration-notes")
# These files make each example runnable, even if a download is incomplete.
REQUIRED_FILES = {
"shared-client": {"README.md", "package.json", "src/index.js", "test/index.test.js"},
"checkout-service": {"README.md", "package.json", "src/checkout.js", "test/checkout.test.js"},
"billing-worker": {"README.md", "package.json", "src/worker.js", "test/worker.test.js"},
"integration-notes": {"README.md"},
"changed-default": {"README.md", "src/index.js", "test/index.test.js"},
"private-helper": {"src/index.js"},
}
def api(method, endpoint, payload=None):
"""Return JSON from GitLab.com using glab's existing authentication.
Inputs are a method, relative REST endpoint, and optional JSON object. Calls
run synchronously; HTTP/CLI errors raise RuntimeError without retrying writes.
No token is read, printed, or stored by this script.
"""
command = ["glab", "api", "--hostname", "gitlab.com", "--method", method, endpoint]
if payload is not None:
command += ["--header", "Content-Type: application/json", "--input", "-"]
result = subprocess.run(command, input=json.dumps(payload) if payload is not None else None,
text=True, capture_output=True, check=False)
if result.returncode:
raise RuntimeError(f"{method} {endpoint}: {result.stderr.strip() or result.stdout.strip()}")
return json.loads(result.stdout)
def file_actions(directory, action):
"""Read the owned text fixtures into deterministic commit actions.
The directory and create/update action determine the returned list. Reads
are local and synchronous; unreadable files propagate an OSError. Hidden
paths are included, but symlinks and installed/generated files are rejected.
"""
actions = []
for path in sorted(directory.rglob("*")):
if path.is_symlink():
raise ValueError(f"Fixture must not be a symlink: {path}")
if not path.is_file():
continue
relative = path.relative_to(directory)
if any(part in {"node_modules", ".git", "__pycache__"} for part in relative.parts):
raise ValueError(f"Unexpected generated fixture: {relative}")
actions.append({"action": action, "file_path": relative.as_posix(),
"content": path.read_text(encoding="utf-8")})
return actions
def main():
"""Preview or create the example and print its URLs; return an exit status.
CLI flags identify the parent and a new subgroup name. Applying requires the
caller's GitLab permissions and glab authentication. Writes are sequential,
aren't rolled back on failure, and never overwrite an existing subgroup.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--parent-group", required=True, help="Existing GitLab.com group path")
parser.add_argument("--name", default="orbit-library-check", help="New private subgroup path")
parser.add_argument("--apply", action="store_true", help="Create the previewed resources")
args = parser.parse_args()
if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", args.name):
parser.error("--name must contain lowercase letters, numbers, and hyphens")
if not re.fullmatch(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*", args.parent_group):
parser.error("--parent-group must be a group path, not a URL")
# Load every fixture before the first external write.
initial = {name: file_actions(FIXTURES / "projects" / name, "create") for name in PROJECTS}
changes = {name: file_actions(FIXTURES / "changes" / name, "update")
for name in ("changed-default", "private-helper")}
if any(not actions for actions in [*initial.values(), *changes.values()]):
raise ValueError("The download is missing fixture files")
for name, actions in {**initial, **changes}.items():
missing = REQUIRED_FILES[name] - {action["file_path"] for action in actions}
if missing:
raise ValueError(f"The download is missing fixture files in {name}: {', '.join(sorted(missing))}")
full_path = f"{args.parent_group}/{args.name}"
print(f"New private subgroup: {full_path}")
print("New private projects: " + ", ".join(PROJECTS))
print("Two open MRs in shared-client; no merges or feature-setting changes.")
if not args.apply:
print("Preview only. Add --apply when you're ready.")
return 0
parent = api("GET", f"groups/{quote(args.parent_group, safe='')}")
group = api("POST", "groups", {"name": args.name, "path": args.name,
"parent_id": parent["id"], "visibility": "private"})
print(f"Created subgroup: {group['web_url']}", flush=True)
projects = {}
for name in PROJECTS:
project = api("POST", "projects", {"name": name, "path": name, "namespace_id": group["id"],
"visibility": "private", "auto_devops_enabled": False})
projects[name] = project
print(f"Created project: {project['web_url']} (ID {project['id']})", flush=True)
api("POST", f"projects/{project['id']}/repository/commits",
{"branch": "main", "commit_message": "Add the library impact example",
"actions": initial[name]})
source = projects["shared-client"]
for case, title in (("changed-default", "Trim account identifiers by default"),
("private-helper", "Rename the internal whitespace helper")):
branch = f"example/{case}"
api("POST", f"projects/{source['id']}/repository/commits",
{"branch": branch, "start_branch": "main", "commit_message": title,
"actions": changes[case]})
mr = api("POST", f"projects/{source['id']}/merge_requests",
{"source_branch": branch, "target_branch": "main", "title": title,
"description": "Compare this proposed library change with the callers in this subgroup. Leave it unmerged while checking the example."})
print(f"{title}: {mr['web_url']}", flush=True)
print(f"\nSearch scope: {full_path}")
print("Project IDs: " + ", ".join(str(project["id"]) for project in projects.values()))
print("Wait for Orbit indexing before starting the Chat questions.")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, ValueError, RuntimeError) as exc:
print(f"Setup stopped: {exc}\nInspect any URLs printed above before trying another new subgroup.", file=sys.stderr)
raise SystemExit(1)