JavaScript "theatre"

         
/**
* Modern Albufeira Prolog Interpreter
*
* Warranty & Liability
* To the extent permitted by applicable law and unless explicitly
* otherwise agreed upon, XLOG Technologies AG makes no warranties
* regarding the provided information. XLOG Technologies AG assumes
* no liability that any problems might be solved with the information
* provided by XLOG Technologies AG.
*
* Rights & License
* All industrial property rights regarding the information - copyright
* and patent rights in particular - are the sole property of XLOG
* Technologies AG. If the company was not the originator of some
* excerpts, XLOG Technologies AG has at least obtained the right to
* reproduce, change and translate the information.
*
* Reproduction is restricted to the whole unaltered document. Reproduction
* of the information is only allowed for non-commercial uses. Selling,
* giving away or letting of the execution of the library is prohibited.
* The library can be distributed as part of your applications and libraries
* for execution provided this comment remains unchanged.
*
* Restrictions
* Only to be distributed with programs that add significant and primary
* functionality to the library. Not to be distributed with additional
* software intended to replace any components of the library.
*
* Trademarks
* Jekejeke is a registered trademark of XLOG Technologies AG.
*/
import {
exec_build, os, VOID_ARGS, engine, path,
exec_deref, is_pending, exec_unify, fs,
launch, launch_async, make_error,
CTX_MAIN, is_special, determine_engine
} from "./machine.mjs";
import {
set, clear, Compound, is_variable, copy_term,
set_stage, stage, check_nonvar, deref,
is_structure
} from "./store.mjs";
import {
atom_count, atom_offset
} from"./eval.mjs";
import {
check_atom, check_integer, check_number, make_check,
MAX_ARITY, narrow_float, norm_smallint,
norm_float, objects_list
} from "./special.mjs";
import {
Source, codebase, Sink, map_stream_error,
set_codebase, bootbase,
put_atom, MASK_SRC_AREAD, MASK_DST_FEAT
} from "./runtime.mjs";
let xml_serializer;
if (fs === undefined) {
xml_serializer = new XMLSerializer();
} else {
xml_serializer = undefined;
}
/**************************************************************/
/* Main API */
/**************************************************************/
/**
* Post a message to the Prolog interpreter.
*
* @param msg The message.
*/
export function post(msg) {
let en = determine_engine(CTX_MAIN);
en.signal = msg;
en.abort();
}
/**
* Run a Prolog term once. The goal is run with auto-yield
* disabled and promises are not accepted.
*
* @param goal The Prolog term.
* @return boolean True or false.
*/
export function perform(goal) {
return launch(goal, CTX_MAIN, VOID_ARGS);
}
/**
* Run a Prolog term once. The goal is run with auto-yield
* enabled and promises are accepted.
*
* @param goal The Prolog term.
* @return boolean True or false.
*/
export async function perform_async(goal) {
return await launch_async(goal, CTX_MAIN, VOID_ARGS);
}
/**************************************************************/
/* Register API */
/**************************************************************/
/**
* The flag indicates a non-void dispatch foreign function.
*/
export const FFI_FUNC = 0x00000100;
/**
* Add a JavaScript function to the knowledge base. The given
* function is invoked with rather slow argument spreading.
* Also the function is wrapped and registered as a
* special, therefore not eligible to neck optimization.
*
* @param functor The functor.
* @param arity The arity.
* @param func The JavaScript function.
* @param flags The flags.
*/
export function register(functor, arity, func, flags) {
let res;
if ((flags & FFI_FUNC) !== 0) {
res = make_check(args => invoke_func(func, args));
} else {
res = make_check(args => invoke(func, args));
}
set(functor, arity, res);
}
function invoke(func, args) {
let temp = new Array(args.length);
for (let i = 0; i < temp.length; i++)
temp[i] = exec_build(args[i]);
func(...temp);
return true;
}
function invoke_func(func, args) {
let temp = new Array(args.length - 1);
for (let i = 0; i < temp.length; i++)
temp[i] = exec_build(args[i]);
let res = func(...temp);
return exec_unify(args[args.length-1], res);
}
/****************************************************************/
/* Element Output */
/****************************************************************/
export function set_cursor(elem) {
let dom = engine.text_output.data;
dom.data = elem;
dom = engine.text_error.data;
dom.data = elem;
}
export function html_encode(buf) {
return xml_serializer.serializeToString(new Text(buf));
}
export function html_send(data, buf) {
buf = html_encode(buf);
put_atom(data, buf);
return data;
}
export function fiddle_flush(data) {
if (data.hasAttribute("cell-clear")) {
data.innerHTML = "";
data.removeAttribute("cell-clear");
}
}
export function fiddle_out(data, buf) {
if (data.hasAttribute("cell-clear")) {
data.innerHTML = "";
data.removeAttribute("cell-clear");
}
let depth = 0;
let k = buf.indexOf("<");
let i = 0;
while (k !== -1) {
let k2 = buf.indexOf(">", k+1);
if (k2 === -1)
throw make_error(new Compound("syntax_error",
["missing_angle"]));
if (buf.charCodeAt(k+1) === 47) { // '/'
if (depth > 0) {
depth--;
} else {
data.insertAdjacentHTML("beforeend", buf.substring(i, k));
data = data.parentElement;
i = k2 + 1;
}
} else if (buf.charCodeAt(k2-1) !== 47) { // '/'
depth++;
}
k = buf.indexOf("<", k2+1);
}
data.insertAdjacentHTML("beforeend", buf.substring(i));
while (depth > 0) {
data = data.lastElementChild;
depth--;
}
return data;
}
/****************************************************************/
/* Text Input */
/****************************************************************/
export function set_input(text) {
let src = engine.text_input;
src.data = undefined;
src.receive = fd => "";
src.flags &= ~MASK_SRC_AREAD;
src.buf = text;
src.pos = 0;
src.lineno = 0;
}
/****************************************************************/
/* Element Input Wait */
/****************************************************************/
/**
* Create a blocking input stream for an element.
*
* @param elem The element.
*/
export function set_caret_wait(elem) {
let src = engine.text_input;
src.data = elem;
src.receive = fiddle_in_promise;
src.flags |= MASK_SRC_AREAD;
src.buf = "";
src.pos = 0;
src.lineno = 0;
}
/**
* Wait for enter key and them obtain the input.
*
* @param en The engine.
* @param stream The stream.
* @returns The wait for promise.
*/
export function fiddle_in_promise(en, stream) {
return new Promise(resolve => {
function keydown_handler(event) {
if (event.key === "Enter") {
event.preventDefault();
let elem = stream.data;
elem.insertAdjacentText("beforeend", "\n");
elem.setAttribute("contenteditable", "false");
elem.insertAdjacentHTML("afterend", "<span></span>");
set_cursor(elem);
stream.data = elem.nextElementSibling;
stream.buf = elem.innerText;
stream.pos = 0;
elem = stream.data.parentElement;
elem.removeEventListener("keydown", keydown_handler);
en.abort = () => {};
resolve();
}
}
let elem = stream.data;
window.getSelection().collapse(elem, 0);
elem.scrollIntoView();
elem = stream.data.parentElement;
elem.addEventListener("keydown", keydown_handler);
en.abort = () => {
elem.removeEventListener("keydown", keydown_handler);
en.abort = () => {};
resolve();
};
});
}
/****************************************************************/
/* Notebook Execution */
/****************************************************************/
/**
* Disable/enable all the buttons.
*
* @param flag Enable if true, other disable.
*/
function shield_buttons(flag) {
let pres = document.getElementsByClassName("nb_box");
for (let num = 0; num < pres.length; num++) {
let btn = pres[num].nextElementSibling;
btn.disabled = flag;
}
}
/**
* Rollback the Prolog interpreter to a stage.
*
* @param num The desired stage.
*/
function rollback_stage(num) {
let pres = document.getElementsByClassName("nb_box");
while (num < stage) {
set_stage(stage-1);
let out = pres[stage].getElementsByClassName("nb_out")[0];
if (num === stage) {
out.setAttribute("cell-clear", "true");
} else {
out.innerHTML = "";
}
clear();
}
}
/**
* Advance the Prolog interpreter to a stage.
*
* @param num The desired stage.
*/
async function advance_async(num) {
let pres = document.getElementsByClassName("nb_box");
while (num >= stage) {
let btn = pres[stage].nextElementSibling;
btn.disabled = false;
btn.firstChild.className = "hack_box";
let out = pres[stage].getElementsByClassName("nb_out")[0];
set_cursor(out);
let txt = pres[stage].getElementsByClassName("nb_txt")[0];
set_input(txt.innerText);
try {
await perform_async(new Compound("ensure_loaded", ["user"]));
await group_gather_async();
perform("flush_output");
} catch (err) {
group_teardown();
perform(new Compound("sys_print_error", [err]));
}
set_stage(stage+1);
btn.disabled = true;
btn.firstChild.className = "hack_arrow";
}
}
/**
* Asynchronously run or abort the Prolog interpreter.
*
* @param form The form.
*/
export async function goto_async(form) {
let pres = document.getElementsByClassName("nb_box");
let num = [].indexOf.call(pres,form);
let btn = form.nextElementSibling;
if (btn.firstChild.className === "hack_arrow") {
shield_buttons(true);
rollback_stage(num);
await advance_async(num);
shield_buttons(false);
} else {
post(new Compound("system_error", ["user_abort"]));
}
}
/**************************************************************/
/* Group */
/**************************************************************/
export function group_teardown() {
/*
for (let i = 0; i < tasks.length; i++) {
let buf = tasks[i];
let msg = new Compound("system_error", ["user_exit"]);
en.signal = msg;
en.abort();
}
*/
}
export async function group_gather_async() {
/*
while (tasks.length > 0) {
solve_signal(null, 0, null);
let prom = notify_promise(CTX_MAIN);
await prom;
}
solve_signal(null, 0, null);
*/
}
function notify_promise(en) {
return new Promise(resolve => {
function handler() {
notify = () => {};
en.abort = () => {};
resolve();
}
notify = handler;
en.abort = () => {
notify = () => {};
en.abort = () => {};
resolve();
};
});
}
/****************************************************************/
/* Document Instrumentation */
/****************************************************************/
/**
* Do the document instrumentation.
*/
export async function instrument_document_async() {
engine.text_output.flags |= MASK_DST_FEAT;
engine.text_error.flags |= MASK_DST_FEAT;
let pres = Array.from(document.querySelectorAll(".code, .raw"));
for (let num = 0; num < pres.length; num++) {
let pre = pres[num];
if (pre.className === "code") {
pre.insertAdjacentHTML("beforebegin", '<div class="nb_flex"></div>');
pre.previousElementSibling.appendChild(pre);
/* modify text */
let text = pre.innerHTML;
text = '<div class="nb_txt" contenteditable="plaintext-only">' + text
+ '</div><div class="nb_out"></div>'
pre.innerHTML = text;
pre.className = "nb_box";
/* create button */
pre.insertAdjacentHTML("afterend", '&nbsp;<button class="nb_btn" disabled>' +
'<div class="hack_arrow"></div>' +
'</button>');
let btn = pre.nextElementSibling;
btn.addEventListener("click", async function () {
await goto_async(pre);
});
btn.disabled = false;
/* instrument text */
let txt = pre.getElementsByClassName("nb_txt")[0];
perform(new Compound("instrument_elem", [txt]));
} else {
/* colorize text */
perform(new Compound("colorize_elem", [pre]));
}
}
}
/*****************************************************************/
/* os_obj_new/1 and os_obj_current/3 */
/*****************************************************************/
/**
* os_obj_new(O):
* The predicate succeeds in O with a new JavaScript object.
*/
function test_os_obj_new(args) {
let res = new Map();
return exec_unify(args[0], res);
}
/**
* os_obj_current(O, K, V):
* The predicate succeeds in V with the value of the key K
* in the JavaScript object O.
*/
function test_os_obj_current(args) {
let obj = exec_build(args[0]);
let key = exec_build(args[1]);
check_atom(key);
let res;
if (obj instanceof Map) {
res = obj.get(key);
} else {
try {
res = obj[key];
} catch (err) {
res = undefined;
}
}
if (res === undefined)
return false;
return exec_unify(args[2], res);
}
/*****************************************************************/
/* os_obj_set/3, os_obj_reset/2 and os_obj_keys/2 */
/*****************************************************************/
/**
* os_obj_set(O, K, V):
* The predicate sets the value of the key K in the
* JavaScript object O to V.
*/
function test_os_obj_set(args) {
let obj = exec_build(args[0]);
let key = exec_build(args[1]);
check_atom(key);
let value = exec_build(args[2]);
if (obj instanceof Map) {
obj.set(key, value);
} else {
try {
obj[key] = value;
} catch (err) {
throw make_error(new Compound("permission_error",
["modify", "field", key]));
}
}
return true;
}
/**
* os_obj_reset(O, K):
* The predicate removes the key K from the JavaScript object O.
*/
function test_os_obj_reset(args) {
let obj = exec_build(args[0]);
let key = exec_build(args[1]);
check_atom(key);
if (obj instanceof Map) {
obj.delete(key);
} else {
try {
delete obj[key];
} catch (err) {
throw make_error(new Compound("permission_error",
["modify", "field", key]));
}
}
return true;
}
/**
* os_obj_keys(O, L):
* The predicate succeeds in L with the keys of
* the JavaScript object O
*/
function test_os_obj_keys(args) {
let obj = exec_build(args[0]);
if (obj instanceof Map) {
obj = obj.keys();
} else {
obj = Object.keys(obj);
}
obj = set_to_list(obj);
return exec_unify(args[1], obj);
}
/**
* Convert a native set into a Prolog list.
*
* @param temp The native set or null.
*/
export function set_to_list(temp) {
let back = null;
let res = null;
if (temp !== null) {
for (let peek of temp) {
peek = new Compound(".", [peek, undefined]);
if (back === null) {
res = peek;
} else {
back.args[1] = peek;
}
back = peek;
}
}
if (back === null) {
res = "[]";
} else {
back.args[1] = "[]";
}
return res;
}
/*********************************************************************/
/* os_float_value/2 and os_atom_offset/3 */
/*********************************************************************/
/**
* os_float_value(P, H):
* If P is instantiated, then the predicate succeeds in H with the
* JavaScript float of P, otherwise in P with the Prolog float of H.
*/
function test_os_float_value(args) {
let alpha = exec_deref(args[0]);
if (is_variable(alpha) || is_pending(alpha)) {
let beta = exec_build(args[1]);
check_number(beta);
let res = (is_special(beta) ? beta :
norm_float(narrow_float(beta)));
return exec_unify(alpha, res);
} else {
alpha = exec_build(alpha);
check_number(alpha);
let res = (is_special(alpha) ? alpha :
narrow_float(alpha));
return exec_unify(args[1], res);
}
}
/**
* os_atom_offset(A, P, H):
* If P is instantiated, then the predicate succeeds in H with
* the JavaScript offset of P into atom A, otherwise in P with the
* Prolog offset of H into the atom A. If the corresponding
* offset exceeds the given atom A the predicate fails.
*/
function test_os_atom_offset(args) {
let alpha = exec_build(args[0]);
check_atom(alpha);
let beta = exec_deref(args[1]);
if (is_variable(beta) || is_pending(beta)) {
let gamma = exec_build(args[2]);
check_integer(gamma);
let at = (0 <= gamma && gamma <= MAX_ARITY ?
narrow_float(gamma) : -1);
if (at < 0 || at > alpha.length)
return false;
let res = atom_count(alpha, 0, at);
return exec_unify(beta, norm_smallint(res));
} else {
beta = exec_build(beta);
check_integer(beta);
let at = (0 <= beta && beta <= MAX_ARITY ?
narrow_float(beta) : -1);
let res = atom_offset(alpha, 0, at);
if (res < 0)
return false;
return exec_unify(args[2], norm_smallint(res));
}
}
/**
* <p>Parse a date time string.</p>
*
* @param res The date time as a string.
* @param pat The pattern.
* @param utc The UTC calendar flag.
* @return The date time in UTC milliseconds.
*/
export function sys_time_parse(res, pat, utc) {
let year = 1900; let month = 1; let day = 1;
let hour = 0; let minute = 0; let second = 0;
let j = 0;
for (let i = 0; i < pat.length; i++) {
let ch = pat.charCodeAt(i);
if (ch === 37) { // %
i++;
let k;
switch (pat.charCodeAt(i)) {
case 37: // %
if (j < res.length && res.charCodeAt(j) === 37) {
j++;
} else {
return NaN;
}
break;
case 97: // a
k = scan_alphanum(res, j);
let f = new Intl.DateTimeFormat((utc !== 0 ? "en-US":undefined), {weekday: "short"});
let weekday = parse_weekday(res.substring(j, k), f);
if (isNaN(weekday))
return NaN;
j = k;
break;
case 98: // b
k = scan_alphanum(res, j);
let g = new Intl.DateTimeFormat((utc !== 0 ? "en-US":undefined), {month: "short"});
month = parse_month(res.substring(j, k), g);
if (isNaN(month))
return NaN;
j = k;
break;
case 100: // d
k = scan_integer(res, j);
day = Number.parseInt(res.substring(j, k));
if (isNaN(day))
return NaN;
j = k;
break;
case 109: // m
k = scan_integer(res, j);
month = Number.parseInt(res.substring(j, k));
if (isNaN(month))
return NaN;
j = k;
break;
case 89: // Y
k = scan_integer(res, j);
year = Number.parseInt(res.substring(j, k));
if (isNaN(year))
return NaN;
j = k;
break;
case 72: // H
k = scan_integer(res, j);
hour = Number.parseInt(res.substring(j, k));
if (isNaN(hour))
return NaN;
j = k;
break;
case 77: // M
k = scan_integer(res, j);
minute = Number.parseInt(res.substring(j, k));
if (isNaN(minute))
return NaN;
j = k;
break;
case 83: // S
k = scan_integer(res, j);
second = Number.parseInt(res.substring(j, k));
if (isNaN(second))
return NaN;
j = k;
break;
default:
return null;
}
} else {
if (j < res.length && res.charCodeAt(j) === ch) {
j++;
} else {
return NaN;
}
}
}
if (utc !== 0) {
return Date.UTC(year, month - 1, day, hour, minute, second);
} else {
return new Date(year, month - 1, day, hour, minute, second).getTime();
}
}
/**
* <p>Scan alphanum.</p>
*
* @param res The text.
* @param j The old position.
* @return The new position.
*/
function scan_alphanum(res, j) {
let ch;
while (j < res.length && ((48 <= (ch = res.charCodeAt(j)) && ch <= 57) ||
(65 <= ch && ch <= 90) ||
(97 <= ch && ch <= 122)))
j++;
return j;
}
/**
* <p>Parse a week day.</p>
*
* @param str The text.
* @param fmt The formatter.
* @return The index.
*/
function parse_weekday(str, fmt) {
str = str.toLowerCase();
for (let i=1; i < 8; i++) {
let wday = new Date(Date.UTC(2001,0,i,0,0,0));
let val = fmt.format(wday);
val = val.toLowerCase();
if (str === val)
return i;
}
return NaN;
}
/**
* <p>Parse a month.</p>
*
* @param str The text.
* @param fmt The formatter.
* @return The index.
*/
function parse_month(str, fmt) {
str = str.toLowerCase();
for (let i=1; i < 13; i++) {
let mon = new Date(Date.UTC(2001,i-1,1,0,0,0));
let val = fmt.format(mon);
val = val.toLowerCase();
if (str === val)
return i;
}
return NaN;
}
/**
* <p>Scan integer.</p>
*
* @param res The text.
* @param j The old position.
* @return The new position.
*/
function scan_integer(res, j) {
let ch;
while (j < res.length && 48 <= (ch = res.charCodeAt(j)) && ch <= 57)
j++;
return j;
}
/*********************************************************************/
/* os_get_gestalt/1 and os_get_host/1 */
/*********************************************************************/
/**
* os_get_gestalt(M): Internal only
* The built-in succeeds in M with a host gestalt map.
*/
function test_os_get_gestalt(args) {
let gestalt = new Map();
let val = (fs !== undefined ? process.env["TERM_SCHEME"] : undefined);
gestalt.set("sys_color", (val !== undefined ? val : "normal"));
let loc = new Intl.DateTimeFormat().resolvedOptions().locale;
gestalt.set("sys_locale", loc.replace("-", "_"));
let res;
if (fs !== undefined) {
res = objects_list(process.argv, 2, process.argv.length - 2);
} else {
res = "[]";
}
gestalt.set("argv", res);
return exec_unify(args[0], gestalt);
}
/**
* os_get_host(M): internal only
* The built-in succeeds in W with a Prolog flag map.
*/
function test_os_get_host(args) {
let res = new Map();
res.set("system_url", bootbase);
res.set("foreign_ext", ".mjs");
if (fs !== undefined) {
res.set("host_info", (process.versions.bun !== undefined ? "Bun" : "Node")+
", JavaScript "+ process.versions.node);
let help = os.version();
let k = help.indexOf(":");
res.set("mach_info", os.cpus()[0].model.trim()+
", "+(k !== -1 ? help.substring(0, k) : help));
} else {
res.set("host_info", "N/A");
res.set("mach_info", "N/A");
}
return exec_unify(args[0], res);
}
/*********************************************************************/
/* os_get_workdir/1 and os_set_workdir/1 */
/*********************************************************************/
/**
* os_get_workdir(D): internal only
* The built-in succeeds in D with the working directory.
*/
function test_os_get_workdir(args) {
let url;
if (fs !== undefined) {
url = process.cwd() + path.sep;
} else {
url = codebase;
}
return exec_unify(args[0], url);
}
/**
* os_set_workdir(D): internal only
* The built-in succeeds. As a side effect it changes the working directory to D.
*/
function test_os_set_workdir(args) {
let url = exec_build(args[0]);
check_atom(url);
if (fs !== undefined) {
try {
process.chdir(url);
} catch (err) {
throw make_error(map_file_error(err, url));
}
} else {
try {
url = new URL(url, codebase).href;
} catch (err) {
throw make_error(new Compound("resource_error", ["base_url"]));
}
set_codebase(url);
}
return true;
}
/*******************************************************************/
/* os_open_promise/4 */
/*******************************************************************/
/**
* os_open_promise(P, L, S, Q):
* The predicate succeeds in Q with a promise for open input S
* on path P and option list L.
*/
function test_os_open_promise(args) {
if (fs === undefined)
throw make_error(new Compound("resource_error",
["not_supported"]));
let name = exec_build(args[0]);
check_atom(name);
let opts = exec_build(args[1]);
let stream = new Source();
if (!exec_unify(args[2], stream))
return false;
return exec_unify(args[3],
open_file_promise(engine, stream, name, opts));
}
export function get_encoding(opts) {
if (opts.get("encoding") !== undefined) {
return opts.get("encoding");
} else {
return "utf8";
}
}
function open_file_promise(en, stream, name, opts) {
return new Promise(resolve => {
fs.open(name, (err, fd) => {
if (!err) {
let enc = get_encoding(opts);
stream.data = fd;
stream.receive = (buf, stream) => file_read_promise(enc, buf, stream);
stream.release = file_close_promise;
stream.partial = Buffer.alloc(0);
stream.flags |= MASK_SRC_AREAD;
} else {
en.signal = map_file_error(err, name);
}
resolve();
});
});
}
export function map_file_error(err, name) {
if (err.code === "ENOENT" || err.code === "ENOTDIR") {
return new Compound("existence_error", ["source_sink", name]);
} else if (err.code === "EISDIR" || err.code === "EACCES") {
return new Compound("permission_error",
["open", "source_sink", name]);
} else {
return new Compound("resource_error", ["io_error"]);
}
}
/*********************************************************************/
/* os_prop_promise/3 */
/*********************************************************************/
/**
* os_prop_promise(F, M, Q):
* The predicate succeeds in Q with with a promise for the
* properties M of the file F. Barks if path F doesn't exist
* or io exception while resolving.
*/
function test_os_prop_promise(args) {
if (fs === undefined)
throw make_error(new Compound("resource_error",
["not_supported"]));
let name = exec_build(args[0]);
check_atom(name);
let res = new Map();
if (!exec_unify(args[1], res))
return false;
return exec_unify(args[2],
prop_file_promise(engine, name, res));
}
function prop_file_promise(en, name, res) {
return new Promise(resolve => {
fs.stat(name, (err, stats) => {
if (!err) {
let ftype = (stats.isFile() ? "regular" :
(stats.isDirectory() ? "directory" : "other"));
res.set("type", ftype);
res.set("absolute_path", (ftype === "directory" ?
path.resolve(name) + path.sep : path.resolve(name)));
res.set("last_modified", norm_smallint(
Math.round(stats.mtimeMs)));
res.set("can_write", ((stats.mode & 0x80) !== 0 ? "true" : "false"));
} else {
if (err.code !== "ENOENT" && err.code !== "ENOTDIR")
en.signal = map_file_error(err, name);
}
resolve();
});
});
}
/******************************************************************/
/* os_open_sync/3 */
/******************************************************************/
/**
* os_open_sync(P, M, L, S):
* The predicate succeeds. As a side effect the stream S is
* opened on the path P with the mode M and the option list L.
*/
function test_os_open_sync(args) {
if (fs === undefined)
throw make_error(new Compound("resource_error",
["not_supported"]));
let name = exec_build(args[0]);
check_atom(name);
let mode = exec_build(args[1]);
check_atom(mode);
let opts = exec_build(args[2]);
let stream;
if ("read" === mode) {
throw make_error(new Compound("resource_error",
["not_supported"]));
} else if ("write" === mode) {
stream = open_write(name, "w", opts);
} else if ("append" === mode) {
stream = open_write(name, "a", opts);
} else {
throw make_error(new Compound("domain_error",
["io_mode", mode]));
}
return exec_unify(args[3], stream);
}
function open_write(name, mode, opts) {
let file;
try {
file = fs.openSync(name, mode);
} catch (err) {
throw make_error(map_file_error(err, name));
}
let enc = get_encoding(opts);
let dst = new Sink();
dst.buf = "";
dst.data = file;
dst.send = (data, buf) => file_write(data, buf, enc);
dst.release = file_close;
return dst;
}
function file_write(data, buf, enc) {
try {
fs.writeSync(data, buf, null, enc);
return data;
} catch (err) {
throw make_error(map_stream_error(err));
}
}
function file_close(data) {
try {
fs.closeSync(data);
} catch (err) {
throw make_error(map_stream_error(err));
}
}
/*********************************************************************/
/* os_cntrl_sync/2 */
/*********************************************************************/
/**
* os_cntrl_sync(F, P):
* The predicate assigns the property P to the file F.
*/
function test_os_cntrl_sync(args) {
if (fs === undefined)
throw make_error(new Compound("resource_error",
["not_supported"]));
let name = exec_build(args[0]);
check_atom(name);
let prop = exec_build(args[1]);
if (is_structure(prop) &&
prop.functor === "last_modified" &&
prop.args.length === 1) {
let val = deref(prop.args[0]);
check_integer(val);
if (val < 0)
throw make_error(new Compound("domain_error",
["not_less_than_zero", val]));
val = new Date(narrow_float(val));
try {
fs.utimesSync(name, val, val);
} catch (err) {
throw make_error(map_file_error(err, name));
}
} else if (is_structure(prop) &&
prop.functor === "can_write" &&
prop.args.length === 1) {
let val = deref(prop.args[0]);
check_atom(val);
if ("true" !== val && "false" !== val)
throw make_error(new Compound("domain_error",
["boolean", val]));
try {
let stats = fs.statSync(name);
if ("true" === val)
fs.chmodSync(name, (stats.mode | 0x80));
else
fs.chmodSync(name, (stats.mode & ~0x80));
} catch (err) {
throw make_error(map_file_error(err, name));
}
} else {
check_nonvar(prop);
prop = copy_term(prop);
throw make_error(new Compound("domain_error",
["file_property", prop]));
}
return true;
}
/******************************************************************/
/* os_http_open_promise/4 */
/******************************************************************/
/**
* os_http_open_promise(P, L, S, Q):
* The predicate succeeds in Q with a promise for open input S
* on path P and option list L.
*/
function test_os_http_open_promise(args) {
let url = exec_build(args[0]);
check_atom(url);
let opts = exec_build(args[1]);
let stream = new Source();
if (!exec_unify(args[2], stream))
return false;
if (fs !== undefined) {
/* */
} else {
try {
url = new URL(url, codebase).href;
} catch (err) {
throw make_error(
new Compound("resource_error", ["base_url"]));
}
}
return exec_unify(args[3],
open_http_promise(engine, stream, url, opts));
}
async function open_http_promise(en, stream, url, opts) {
let paras = {};
if (opts.get("method") !== undefined) {
paras.method = opts.get("method");
} else if (opts.get("body") !== undefined) {
paras.method = "POST";
} else {
paras.method = "GET";
}
if (opts.get("body") !== undefined) {
let opts2 = opts.get("body");
if (fs !== undefined) {
let enc = get_encoding(opts2);
paras.body = Buffer.from(opts2.get("text"), enc);
} else {
paras.body = opts2.get("text");
}
}
if (opts.get("headers") !== undefined)
paras.headers = opts.get("headers");
let contr = new AbortController();
paras.signal = contr.signal;
en.abort = () => contr.abort("ABORT");
try {
let response = await fetch(url, paras);
en.abort = () => {};
if (200 <= response.status && response.status <= 399) {
opts.set("uri", response.url);
opts.set("status", response.status);
let res = new Map();
let map = response.headers;
for (let key of map.keys())
res.set(key, map.get(key));
opts.set("fields", res);
if (!response.body) {
/* */
} else {
let enc = get_encoding(opts);
stream.data = response.body.getReader();
stream.receive = (en, stream) => http_read_promise(enc, en, stream);
stream.release = http_close_promise;
stream.flags |= MASK_SRC_AREAD;
}
} else {
en.signal = map_http_result(response.status, url);
}
} catch (err) {
en.abort = () => {};
if ("ABORT" !== err)
en.signal = map_net_error(err, url);
}
}
async function http_read_promise(enc, en, stream) {
try {
let {done, value} = await stream.data.read();
let res;
if (done) {
res = "";
} else {
if (fs !== undefined) {
res = Buffer.from(value.buffer).toString(enc);
} else {
let txt = new TextDecoder("utf8");
res = txt.decode(value);
}
}
stream.buf = res;
stream.pos = 0;
} catch (err) {
en.signal = map_stream_error(err);
}
}
function http_close_promise(buf, stream) {
return stream.data.cancel();
}
export function map_net_error(err, url) {
let code = (err.cause !== undefined ? err.cause.code : "");
if (code === "ENOTFOUND") {
return new Compound("existence_error", ["host", url]);
} else if (code === "ETIMEDOUT") {
return new Compound("resource_error", ["connect_failed"]);
} else {
return new Compound("resource_error", ["remote_error"]);
}
}
export function map_http_result(res, url) {
switch (res) {
case 403: // Forbidden
return new Compound("permission_error",
["open", "source_sink", url]);
case 404: // Not Found
return new Compound("existence_error",
["source_sink", url]);
case 405: // Method Not Allowed
return new Compound("resource_error",
["illegal_method"]);
case 500: // Internal Server Error
return new Compound("resource_error",
["internal_error"]);
case 503: // Service Unavailable
return new Compound("resource_error",
["service_unavailable"]);
default:
return new Compound("resource_error",
["io_exception"]);
}
}
/*******************************************************************/
/* os_http_prop_promise/3 */
/*******************************************************************/
const HTTP_TIME = "%a, %d %b %Y %H:%M:%S GMT";
/**
* os_http_prop_promise(F, M, Q):
* The predicate succeeds in Q with with a promise for the
* properties M of the file F. Barks if path F doesn't exist
* or io exception while resolving.
*/
function test_os_http_prop_promise(args) {
let url = exec_build(args[0]);
check_atom(url);
let res = new Map();
if (!exec_unify(args[1], res))
return false;
if (fs !== undefined) {
/* */
} else {
try {
url = new URL(url, codebase).href;
} catch (err) {
throw make_error(
new Compound("resource_error", ["base_url"]));
}
}
return exec_unify(args[2],
prop_http_promise(engine, url, res));
}
async function prop_http_promise(en, url, res) {
let paras = {};
paras.method = "HEAD";
let contr = new AbortController();
paras.signal = contr.signal;
en.abort = () => contr.abort("ABORT");
try {
let response = await fetch(url, paras);
en.abort = () => { };
if (200 <= response.status && response.status <= 399) {
let val = response.headers.get("Last-Modified");
let mtime = (val !== null ? sys_time_parse(
val, HTTP_TIME, 1) : -1);
res.set("last_modified", norm_smallint(mtime));
res.set("absolute_path", response.url);
res.set("type", "regular");
res.set("can_write", "false");
} else {
if (response.status !== 404)
en.signal = map_http_result(response.status, url);
}
} catch(err) {
en.abort = () => {};
if ("ABORT" !== err)
en.signal = map_net_error(err, url);
}
}
/*******************************************************************/
/* os_http_open_sync/3 */
/*******************************************************************/
/**
* os_http_open_sync(P, M, L, S):
* The predicate succeeds. As a side effect the stream S is
* opened on the path P with the mode M and the option list L.
*/
function test_os_http_open_sync(args) {
let url = exec_build(args[0]);
check_atom(url);
throw make_error(new Compound("permission_error",
["access", "source_sink", url]));
}
/**
* os_http_cntrl_sync(F, P):
* The predicate assigns the property P to the file F.
*/
function test_os_http_cntrl_sync(args) {
let url = exec_build(args[0]);
check_atom(url);
throw make_error(new Compound("permission_error",
["access", "source_sink", url]));
}
/*********************************************************************/
/* Theatre Init */
/*********************************************************************/
// system specials, host
set("os_obj_new", 1, make_check(test_os_obj_new));
set("os_obj_current", 3, make_check(test_os_obj_current));
set("os_obj_set", 3, make_check(test_os_obj_set));
set("os_obj_reset", 2, make_check(test_os_obj_reset));
set("os_obj_keys", 2, make_check(test_os_obj_keys));
// system specials, types
set("os_float_value", 2, make_check(test_os_float_value));
set("os_atom_offset", 3, make_check(test_os_atom_offset));
// stream specials, gestalt
set("os_get_gestalt", 1, make_check(test_os_get_gestalt));
set("os_get_host", 1, make_check(test_os_get_host));
set("os_get_workdir", 1, make_check(test_os_get_workdir));
set("os_set_workdir", 1, make_check(test_os_set_workdir));
// stream specials, file
set("os_open_promise", 4, make_check(test_os_open_promise));
set("os_prop_promise", 3, make_check(test_os_prop_promise));
set("os_open_sync", 4, make_check(test_os_open_sync));
set("os_cntrl_sync", 2, make_check(test_os_cntrl_sync));
// stream specials, net
set("os_http_open_promise", 4, make_check(test_os_http_open_promise));
set("os_http_prop_promise", 3, make_check(test_os_http_prop_promise));
set("os_http_open_sync", 4, make_check(test_os_http_open_sync));
set("os_http_cntrl_sync", 2, make_check(test_os_http_cntrl_sync));